Search⌘ K

Rotate Matrix, Advanced

Explore how to rotate a square matrix 90 degrees clockwise directly within the original array, using an in-place algorithm. Understand the step-by-step layering approach and swapping logic, and analyze the time and space complexities. This lesson develops skills in spatial reasoning and efficient data manipulation for JavaScript interviews.

Rotate Square Matrix in Place

147258369

⬇️

789456123

Instructions

Write a function that takes a square matrix as input. A square matrix has the same number of rows and columns, e.g. 3 x 3, 4 x 4, 5 x 5. It should return the same matrix rotated 90 degrees clockwise. The rotation should happen in place, meaning you may not create any extra matrixes or arrays in your function.

Input: Array of arrays of numbers

Output: Array of arrays of numbers

Example

An input of:

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

yields an output of:

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

Hints

  1. Start at the border and work your way in.
  2. We’ll need some placeholder variables.

Node.js
function rotateClockwise(mat) {
// Your code here
}

Solution

Node.js
function rotateClockwise(mat) {
const totalLayers = Math.floor(mat.length / 2);
for(let layer = 0; layer < totalLayers; layer++) {
const lastIndex = mat.length - 1 - layer;
for(let forwardIterator = layer + 1; forwardIterator < mat.length - layer; forwardIterator++) {
const reverseIterator = lastIndex - forwardIterator + layer;
let temp1 = mat[forwardIterator][lastIndex];
mat[forwardIterator][lastIndex] = mat[layer][forwardIterator];
let temp2 = mat[lastIndex][reverseIterator];
mat[lastIndex][reverseIterator] = temp1;
temp1 = mat[reverseIterator][layer];
mat[reverseIterator][layer] = temp2;
mat[layer][forwardIterator] = temp1;
}
}
return mat;
}

The Strategy

We’ll treat the input matrix as a series of nested layers. We’ll start from the outermost layer and work our way towards the center. Here’s what that means, in terms of a 5x5 matrix. ...