v9.1.1
Menu

Reshape the Matrix

easyPROArrays & Matrix OperationsDSA for AI Engineers

Given an m x n matrix, reshape it to r x c. If not possible (i.e. m⋅n≠r⋅cm \cdot n \ne r \cdot c), return the original matrix.

Implement reshape(matrix, r, c), which returns the new matrix as a list of r rows. Elements keep their row-major order: read the original left to right, top to bottom, and fill the new matrix in the same order.

Output each row on a line, space-separated.

Example

Input
1,2
3,4
1 4
Output
1 2 3 4
Reasoning
  • matrix is a 2×22 \times 2 grid: the first row holds 1,21, 2 and the second row holds 3,43, 4. The last input line is the target shape, r=1r = 1 row and c=4c = 4 columns.
  • A reshape never adds or drops values, so it is only possible when the element counts agree: m⋅n=2⋅2=4m \cdot n = 2 \cdot 2 = 4 and r⋅c=1⋅4=4r \cdot c = 1 \cdot 4 = 4. They match, so the reshape happens.
  • The values keep their row-major reading order (left to right across the first row, then the second), giving the sequence 1,2,3,41, 2, 3, 4. The new grid is filled in that same order, c=4c = 4 values per row, so all four land in the single row.
  • The result is one row, printed as 1 2 3 4.
  • Notice what happens with a target of 2×42 \times 4: that needs 88 elements but only 44 exist, so the original matrix comes back unchanged and prints as 1 2 and 3 4 on two lines.

Constraints

  • 1 <= m, n <= 100

More from DSA for AI Engineers

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.