Reshape the Matrix (LeetCode 566): Solution and Explanation

Easy
Array
Matrix
Simulation

Given an m x n matrix and a target shape r x c, rebuild the matrix with the same values in the same row-major order. When the target cannot hold exactly m * n values, return the original matrix.

Intuition

Read any matrix row by row and you get one long sequence of values. Reshaping does not change that sequence at all. It only changes where the sequence is cut into rows: every n values for the input, every c values for the output.

So give each value a single position k in that sequence. Position k lives at row k // n, column k % n of the input, and at row k // c, column k % c of the output.

The only way to fail is a size mismatch. If r * c is not m * n, the sequence would either run out early or leave values behind, so the problem says to return mat unchanged.

Approach: Single flat index

  1. Let m = len(mat) and n = len(mat[0]). If m * n != r * c, return mat.
  2. Allocate res with r rows and c columns.
  3. For k from 0 to m * n - 1, set res[k // c][k % c] = mat[k // n][k % n].
  4. Return res.

Step-by-step example

mat = [[1,2],[3,4]], r = 1, c = 4
  1. m = 2, n = 2, so mat holds 4 values. r * c = 1 * 4 = 4, so the reshape is legal.
  2. Allocate a 1 x 4 result.
  3. k = 0: mat[0][0] = 1 goes to res[0][0]. k = 1: mat[0][1] = 2 goes to res[0][1].
  4. k = 2: mat[1][0] = 3 goes to res[0][2]. k = 3: mat[1][1] = 4 goes to res[0][3].
  5. The result is [[1,2,3,4]].

Code: Python, Java, C++

1class Solution:
2    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
3        m, n = len(mat), len(mat[0])
4        if m * n != r * c:
5            return mat
6        res = [[0] * c for _ in range(r)]
7        for k in range(m * n):
8            res[k // c][k % c] = mat[k // n][k % n]
9        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each value is read once and written once.

Space

O(m * n)

The output holds m * n values; besides it only the index k is used.

Other approaches

Flatten then cut (time O(m * n), space O(m * n))

Build a flat list of all values, then slice it into rows of length c. Easy to read, but it stores the values twice.

Two moving cursors (time O(m * n), space O(m * n))

Walk the input with (i, j) and the output with (row, col), advancing the output column and wrapping to the next row when it reaches c. Same work as the flat index, with more bookkeeping.

Common mistakes

  • Dividing by the wrong width: the input uses n and the output uses c.
  • Returning an empty matrix instead of mat when the sizes do not match.
  • Using integer division in a language where / gives a float (JavaScript needs Math.floor).
  • Building rows with [[0] * c] * r in Python, which shares one list across all rows.

Frequently asked questions

When is a reshape impossible?

Exactly when r * c is different from m * n. The target would need more or fewer values than the matrix has, so the original matrix is returned.

Why does the flat index formula work?

In row-major order, row i starts at position i * width. So position k is in row k // width at column k % width. Using the input width for reading and the output width for writing keeps the order identical.

What is the time and space complexity of Reshape the Matrix?

O(m * n) time to copy every value once, and O(m * n) space for the returned matrix.