Reshape the Matrix

You are given an `m x n` matrix `mat` and two integers `r` and `c`. Reshape `mat` into a new `r x c` matrix that holds the same values in the same row-major order: read `mat` row by row, left to right, and fill the new matrix row by row in that order. If an `r x c` matrix cannot hold exactly the same number of values (`m * n != r * c`), return the original `mat` unchanged.

30:00

Reshape the Matrix
easy
Free written solution
Topics
Companies

You are given an m x n matrix mat and two integers r and c. Reshape mat into a new r x c matrix that holds the same values in the same row-major order: read mat row by row, left to right, and fill the new matrix row by row in that order.

If an r x c matrix cannot hold exactly the same number of values (m * n != r * c), return the original mat unchanged.

Example 1:
Input: {"mat":[[1,2],[3,4]],"r":1,"c":4}
Output: [[1,2,3,4]]
Constraints:
  • m==mat.lengthm == \text{mat.length}

  • n==mat[i].lengthn == \text{mat}[i].\text{length}

  • 1≤m,n≤1001 \leq m, n \leq 100

  • −1000≤mat[i][j]≤1000-1000 \leq \text{mat}[i][j] \leq 1000

  • 1≤r,c≤3001 \leq r, c \leq 300

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"mat":[[1,2],[3,4]],"r":1,"c":4}

mat is 2 x 2, so it holds 4 values. Read row by row, they form one long tape: [1, 2, 3, 4].

mat[k // 2][k % 2] → res[k // 4][k % 4]

mat (2 x 2)

1
2
3
4

→

res (1 x 4)

row-major tape (k = 0..3)

1
2
3
4

Cut this tape every 2 values and you get mat; cut it every 4 values and you get the reshaped matrix. The colour follows k.

Variables
VariableValue
m2
n2
r1
c4
DepthFunction Call
Stack empty
0/7