Reshape the Matrix

Easy
278.

Reshape the Matrix

Reshape the Matrix is an easy coding problem on arrays, matrix and simulation, asked in Amazon, Microsoft, Adobe and MathWorks interviews.

You are given an m × n matrix mat and two integers r and c giving the number of rows and columns of a wanted reshaped matrix.

The reshaped matrix must contain all the original elements in the same row-traversing order. If the reshape is not legal — the element counts differ — return the original matrix.

Example 1

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

Example 2

Input
mat = [[1,2],[3,4]], r = 2, c = 4
Output
[[1,2],[3,4]]
Explanation
4 elements cannot fill 8 slots, so the original is returned.

Example 3

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

Constraints

  • 1 <= mat.length, mat[i].length <= 8
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 40
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {number[][]} mat
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
var matrixReshape = function(mat, r, c) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Reshape the Matrix — Solution in Python, Java & C++

Reshape the Matrix solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and matrix.

Reshape the Matrix is an easy coding problem on arrays, matrix and simulation, asked in Amazon, Microsoft, Adobe and MathWorks interviews.

Problem statement

You are given an m × n matrix mat and two integers r and c giving the number of rows and columns of a wanted reshaped matrix.

The reshaped matrix must contain all the original elements in the same row-traversing order. If the reshape is not legal — the element counts differ — return the original matrix.

Example 1

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

Example 2

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Explanation: 4 elements cannot fill 8 slots, so the original is returned.

Example 3

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

Constraints

  • 1 <= mat.length, mat[i].length <= 8
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 40

Hints for Reshape the Matrix

  1. Hint 1

    Check m × n == r × c first; anything else returns the input unchanged.

  2. Hint 2

    Flatten in row order, then slice into rows of length c.

  3. Hint 3

    Without flattening: element k of the reading order sits at (k / n, k % n) in the source and (k / c, k % c) in the target.

How to solve Reshape the Matrix

If the element counts match, read the matrix in row order and cut it into rows of length c.

Approach

  1. Return mat unchanged if m · n != r · c.
  2. Flatten row by row.
  3. Slice the flat list into r rows of c elements.

Why it works

Reshaping preserves the row-major reading order, so the flat sequence is the invariant and only the row breaks move.

Complexity

  • Time — O(m · n)
  • Space — O(m · n)

Pitfalls

  • Index arithmetic (flat[k] at (k // n, k % n) → (k // c, k % c)) avoids the intermediate list.

Reference solution

Python

def matrixReshape(mat, r: int, c: int):
    rows, cols = len(mat), len(mat[0])
    if rows * cols != r * c:
        return mat
    flat = [v for row in mat for v in row]
    return [flat[i * c:(i + 1) * c] for i in range(r)]

Java

public static int[][] matrixReshape(int[][] mat, int r, int c) {
    int rows = mat.length, cols = mat[0].length;
    if (rows * cols != r * c) return mat;
    int[][] out = new int[r][c];
    for (int k = 0; k < r * c; k++) {
        out[k / c][k % c] = mat[k / cols][k % cols];
    }
    return out;
}

C++

vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
    int rows = (int) mat.size(), cols = (int) mat[0].size();
    if (rows * cols != r * c) return mat;
    vector<vector<int>> out(r, vector<int>(c, 0));
    for (int k = 0; k < r * c; k++) {
        out[k / c][k % c] = mat[k / cols][k % cols];
    }
    return out;
}

JavaScript

var matrixReshape = function(mat, r, c) {
    const rows = mat.length, cols = mat[0].length;
    if (rows * cols !== r * c) return mat;
    const flat = [];
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) flat.push(mat[i][j]);
    }
    const out = [];
    for (let i = 0; i < r; i++) out.push(flat.slice(i * c, i * c + c));
    return out;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 1199 arrays problems · the whole catalogue

Learn the technique: Arrays · Matrix and Grid Traversal