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

1/**
2 * @param {number[][]} mat
3 * @param {number} r
4 * @param {number} c
5 * @return {number[][]}
6 */
7var matrixReshape = function (mat, r, c) {
8 const [m, n] = [mat.length, mat[0].length]
9
10 if (m * n !== r * c) {
11 return mat
12 }
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 newMatrix
24}

Comments

Loading comments...

Tags

leetcode

array

matrix

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

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

HoningJS

Search Posts