Search⌘ K

Rotate Matrix

Explore how to create a function that rotates a matrix 90 degrees clockwise in JavaScript. Understand matrix transformations for both square and rectangular arrays, and learn to analyze the time and space complexity of your solution. Gain insight into alternative rotation methods and how to extend your function to rotate matrices counter-clockwise or by 180 degrees.

Rotate Matrix

147258369

⬇️

789456123

Instructions

A matrix in JavaScript can be represented as an array of arrays. For example, here is a 3 x 3 matrix:

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

Write a function that takes a matrix as input and returns a new matrix. This new matrix should represent the original matrix rotated 90 degrees clockwise. The original matrix should be unchanged. This function should work for both square and rectangular matrixes.

Input: Array of Arrays of Numbers

Output: Array of Arrays of Numbers

Example

When given the matrix above as input, the output should be:

 ...