Problem Walkthrough

Reshape Matrix LeetCode 566 Guide

Flatten the matrix conceptually to a 1D index using i*n + j, then map each element to its new row and column positions in the reshaped matrix using divmod — no actual flat array needed, just arithmetic on indices.

7 min read|

Reshape Matrix

LeetCode 566

Problem Overview

LeetCode 566 Reshape the Matrix asks you to convert an m x n matrix mat into a new r x c matrix. The elements must be filled in the same row-traversal order as they appear in the original — left to right, top to bottom — so the relative order of all elements is preserved.

If m * n does not equal r * c, the reshape is impossible and you must return the original matrix mat unchanged. This is the single edge case to handle before doing any real work. When the total element count matches, a valid reshape always exists.

The problem is a classic index mapping exercise. Understanding how to move between 2D coordinates and a flat linear index is the core skill tested, and it applies to many other matrix manipulation problems.

  • Reshape m x n matrix mat into a new r x c matrix
  • Fill in row-traversal order: left to right, top to bottom
  • If m*n != r*c, return the original matrix unchanged
  • Otherwise rearrange elements into the new r x c shape

1D Index Mapping

Every element at position (i, j) in an m x n matrix has a unique linear index: index = i * n + j. This maps the 2D grid to a flat sequence numbered 0 through m*n-1, following the same row-major order that the problem requires.

Given a linear index and the new column count c, the new row and column are: newRow = index // c and newCol = index % c. This is integer division and modulo — often called divmod. Together, these two formulas connect the original 2D position to the reshaped 2D position without ever constructing an intermediate flat array.

The relationship is bijective when m*n == r*c: every index maps to exactly one source cell and exactly one destination cell. This is why the check comes first — without it the mapping would produce out-of-bounds indices.

💡

You Never Need to Flatten

You do not need to actually flatten the matrix into a 1D list. The divmod trick maps between any two 2D layouts that share the same total number of elements using pure arithmetic. Compute index = i*n + j once, then write directly to result[index // c][index % c].

Algorithm

The algorithm is a straightforward nested loop over the original matrix. For each cell (i, j), compute its linear index, then derive the destination row and column in the new matrix using divmod. Write the value and continue.

Because each element is visited exactly once and each write goes to a unique destination cell, the algorithm is correct for any valid (r, c) pair. The output matrix is filled completely after one pass through the input.

Time complexity is O(m*n) — one pass over every element. Space complexity is O(1) extra beyond the output matrix, which the problem expects as the return value and does not count against the space budget.

  1. 1If m * n != r * c, return mat immediately
  2. 2Create a new r x c matrix result initialized to zeros
  3. 3For each row i in 0..m-1: for each col j in 0..n-1:
  4. 4 Compute index = i * n + j
  5. 5 Set result[index // c][index % c] = mat[i][j]
  6. 6Return result

Python One-Liner with numpy-style

Python allows a compact one-liner using list comprehension and itertools.chain: flat = list(itertools.chain.from_iterable(mat)); return [flat[i*c:(i+1)*c] for i in range(r)]. This is Pythonic and readable but does allocate an intermediate flat list of size m*n.

An alternative without itertools: flat = [mat[i][j] for i in range(m) for j in range(n)]. The slicing approach [flat[i*c:(i+1)*c] for i in range(r)] then rebuilds the rows. Both variants are O(m*n) time and O(m*n) extra space for the flat list.

The divmod nested-loop approach avoids the extra flat list entirely and writes directly to the result matrix, making it more memory-efficient in practice even though the asymptotic space class is the same since the output is O(m*n) regardless.

ℹ️

NumPy Has reshape Built In

Python's numpy library has a reshape method built in — numpy.array(mat).reshape(r, c).tolist() — but LeetCode expects pure Python solutions. The divmod approach replicates numpy's index arithmetic manually and works in any language without extra libraries.

Walk-Through Example

Consider mat = [[1, 2], [3, 4]], r = 1, c = 4. Check: m*n = 2*2 = 4, r*c = 1*4 = 4 — equal, so reshape is valid. Create result = [[0, 0, 0, 0]].

Iterate: (i=0, j=0): index=0, result[0//4][0%4] = result[0][0] = 1. (i=0, j=1): index=1, result[0][1] = 2. (i=1, j=0): index=2, result[0][2] = 3. (i=1, j=1): index=3, result[0][3] = 4.

Result = [[1, 2, 3, 4]]. All four elements appear in row-traversal order in a single row of four columns, which is exactly what r=1, c=4 specifies.

  1. 1mat=[[1,2],[3,4]], r=1, c=4 — check 2*2==1*4 ✓
  2. 2index 0 → result[0//4][0%4] = result[0][0] = 1
  3. 3index 1 → result[1//4][1%4] = result[0][1] = 2
  4. 4index 2 → result[2//4][2%4] = result[0][2] = 3
  5. 5index 3 → result[3//4][3%4] = result[0][3] = 4
  6. 6Return [[1, 2, 3, 4]]

Code Walkthrough — Python and Java

Python solution: def matrixReshape(mat, r, c): m, n = len(mat), len(mat[0]); if m*n != r*c: return mat; result = [[0]*c for _ in range(r)]; for i in range(m): for j in range(n): idx = i*n+j; result[idx//c][idx%c] = mat[i][j]; return result. The nested loop with divmod is about 8 lines and handles all cases cleanly.

Java solution: if (m*n != r*c) return mat; int[][] result = new int[r][c]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) { int idx = i*n+j; result[idx/c][idx%c] = mat[i][j]; } return result. Java uses / for integer division and % for modulo, so the arithmetic is identical.

Time complexity: O(m*n) — every element is read once and written once. Space complexity: O(1) extra — the output matrix is the return value and does not count as extra space. No intermediate data structures are used beyond the result array.

⚠️

Always Check m*n == r*c First

Always verify m*n == r*c before allocating the result matrix or iterating. If the totals do not match, return the original matrix mat unchanged immediately. This is the only edge case in the problem and skipping it leads to out-of-bounds index errors in the divmod arithmetic.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now