# LeetCode: Reshape the Matrix Solution

Flat, reverse, and pop

## Approach

Steps:

• init new matrix
• flatten the input matrix, and reverse it
• pop each of the reversed flatten matrix into each of the new matrix element

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[][]} mat3 * @param {number} r4 * @param {number} c5 * @return {number[][]}6 */7var matrixReshape = function (mat, r, c) {8  const [m, n] = [mat.length, mat.length]9
10  if (m * n !== r * c) {11    return mat12  }13
14  const newMatrix = Array.from({ length: r }, _ => Array(c))15  const reversedFlattenMatrix = mat.flat().reverse()16
17  for (let row = 0; row < r; row++) {18    for (let col = 0; col < c; col++) {19      newMatrix[row][col] = reversedFlattenMatrix.pop()20    }21  }22
23  return newMatrix24}```

leetcode

array

matrix

## Next Post

LeetCode: Kth Smallest Element in a Sorted Matrix

Jul 7, 2021

Flatten and sort

## Previous Post

LeetCode: Count Vowels Permutation

Jul 4, 2021

Memoized recursion

Search Posts