418/670

418. Reshape the Matrix

Easy

You are handed a matrix mat of integers with m rows and n columns, plus two integers r and c describing a desired new shape.

Build and return an r × c matrix that holds every value of mat in the same row-major reading order — left to right across a row, then down to the next row — exactly the order you'd read mat like text on a page.

If the new shape can't hold the data (that is, r * c ≠ m * n), the reshape is invalid: return the original matrix unchanged.

Reshape keeps the reading orderReshaping [[1, 2], [3, 4]] into 1 × 4: read the old grid left-to-right, top-to-bottom, and pour the values into the new shape in the same order.
mat (2 × 2)1234reading order: 1, 2, 3, 4r = 1, c = 4result (1 × 4)1234k=0k=1k=2k=3same values, new line breaks

Example 1:

Input: mat = [[1, 2], [3, 4]], r = 1, c = 4

Output: [[1, 2, 3, 4]]

Explanation: Reading mat row by row gives 1, 2, 3, 4. Those four values fill a single row of four columns.

Example 2:

Input: mat = [[1, 2], [3, 4]], r = 2, c = 4

Output: [[1, 2], [3, 4]]

Explanation: The target has 2 × 4 = 8 slots but mat only carries 4 values, so the reshape is invalid and mat itself comes back.

Constraints:

  • 1 ≤ m, n ≤ 100
  • -1000 ≤ mat[i][j] ≤ 1000
  • 1 ≤ r, c ≤ 300

Hints:

Picture reading the matrix like text on a page: left to right, top to bottom. Reshaping keeps that reading order and only moves where the line breaks fall.

Give every value a single reading-order index k. It sits at row k / n, column k % n of the old grid — and belongs at row k / c, column k % c of the new one. One pass, no intermediate list.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: mat = [[1, 2], [3, 4]], r = 1, c = 4

Expected output: [[1, 2, 3, 4]]