Skip to content
Problem 566 · LeetCode 566(opens in a new tab)

Reshape the Matrix

EasyArrays

You are given a matrix mat with m rows and n columns, and two numbers r and c. Rebuild the same values as a new matrix with r rows and c columns.

Read mat row by row, left to right, and write the values into the new matrix in that same order, also row by row. If r × c is not equal to m × n, the values cannot fit exactly, so return mat unchanged.

Example 1

Input:  mat = [[5, 7, 9], [2, 4, 6]], r = 3, c = 2
Output: [[5, 7], [9, 2], [4, 6]]
Why:    the order 5 7 9 2 4 6 is cut into rows of 2
2 more examples and the constraints

Example 2

Input:  mat = [[8, 3], [1, 0]], r = 3, c = 2
Output: [[8, 3], [1, 0]]
Why:    3 × 2 = 6 cells, but there are only 4 values

Example 3

Input:  mat = [[−4], [6], [2]], r = 1, c = 3
Output: [[−4, 6, 2]]
Why:    a column of 3 becomes a single row

Constraints

  • 1 ≤ m, n ≤ 100
  • 1 ≤ r, c ≤ 300
  • −1,000 ≤ mat[i][j] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Flatten, then cut into rowsO(m·n)
  2. Map one index to twoO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 100 × 100 matrixVerdict
Flatten, then cut into rowsO(m·n)
Clear; one extra list
Map one index to twoO(m·n)
Best; no extra list

m, n = rows and columns of mat.

Edge cases to test

  • Sizes that do not match. 2 × 2 values cannot fill 3 × 2 cells; return mat itself.
  • Same shape as before. r = m and c = n gives a copy of mat.
  • One row or one column. r = 1 lays every value in a single row; c = 1 stacks them in one column.
  • A single value. [[7]] with r = c = 1 returns [[7]].

Common mistakes

  • Dividing by the wrong width: the old position uses n (columns of mat), the new one uses c.
  • Checking r ≤ m or c ≤ n instead of comparing the total counts m × n and r × c.
  • Filling the result column by column, which keeps the values but breaks the reading order.

How to talk through it

  1. 1Clarify. Is the order row by row in both matrices? What should come back when the sizes do not match?
  2. 2Check the sizes. The reshape works only when m × n equals r × c; otherwise return mat.
  3. 3Name the order. Number the values in reading order. Both matrices share that order.
  4. 4Map the index. Value k lives at (k / n, k % n) in mat and goes to (k / c, k % c) in the result.
  5. 5Test out loud. Try a mismatch, a single row, a single column, and a 1 × 1 matrix.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?