Skip to main content
Back to problems
Leetcode
Easy
Arrays
Matrices
Reshape The Matrix

Reshape a matrix into a new size while preserving the original row-major order of its elements.

Acceptance 0%
Problem Statement

Problem

Given an m×nm \times n matrix, reshape it into a new matrix with dimensions r×cr \times c.

The reshaping must keep the elements in the same row-major order as the original matrix. If the reshape is not possible because the total number of elements does not match, return the original matrix unchanged.

Notes

  • Elements must be read left to right, top to bottom.
  • The new matrix should also be filled left to right, top to bottom.
  • If m×nr×cm \times n \ne r \times c, no valid reshape exists.

Input Format

  • A 2D integer matrix mat
  • Two integers r and c representing the desired number of rows and columns

Output Format

  • Return the reshaped matrix if possible
  • Otherwise return the original matrix

Constraints

  • 1 <= m, n <= 100
  • 1 <= r, c <= 100
  • The matrix contains integers
  • The total number of elements may or may not match the requested shape
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

[[1,2,3,4]]

Explanation

The matrix has 4 elements, and 1×4=41 \times 4 = 4, so reshaping is valid. The row-major order is preserved.

Example 2

Input

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

Output

[[1,2],[3,4]]

Explanation

The matrix has 4 elements, but 2×3=62 \times 3 = 6, so reshaping is impossible. Return the original matrix.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.