Skip to main content
Back to problems
#566
Easy Algorithms

Reshape the matrix

Array Matrix Simulation
64.7% acceptance
Jan 13, 2026
3694
437
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {
    let (m, n) = (mat.len() as i32, mat[0].len() as i32);
    if m * n != r * c { return mat; }
    let flat: Vec<i32> = mat.into_iter().flatten().collect();
    flat.chunks(c as usize).map(|chunk| chunk.to_vec()).collect()
  }
}