Rotate Image - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

To rotate an n Γ— n matrix 90Β° clockwise in place, we perform two sequential in-place transformations:

  1. Step 1 β€” Transpose the matrix: Swap matrix[rowIndex][colIndex] ↔ matrix[colIndex][rowIndex] for all index pairs (rowIndex, colIndex) above the main diagonal, effectively converting rows into columns.
    • Outer loop (rowIndex): The loop runs from rowIndex = 0 to n βˆ’ 1. At each iteration, we complete the transpose of row rowIndex by moving every element matrix[rowIndex][colIndex] (where colIndex > rowIndex) to its symmetric position matrix[colIndex][rowIndex] below the main diagonal. After this iteration, both the rowIndexth row and rowIndexth column are fully transposed and will not be revisited. When advancing to the next iteration rowIndex + 1, the algorithm naturally focuses on the smaller submatrix [rowIndex+1..nβˆ’1] Γ— [rowIndex+1..nβˆ’1].
    • Inner loop (colIndex): The inner loop starts at colIndex = rowIndex + 1 and runs to n βˆ’ 1, visiting only the cells above the diagonal in the top row of the current submatrix matrix[rowIndex..nβˆ’1][rowIndex..nβˆ’1]. Each visited cell matrix[rowIndex][colIndex] is swapped exactly once with its symmetric counterpart matrix[colIndex][rowIndex] below the diagonal.
    • No double-swapping: Because the inner loop begins after the diagonal (colIndex = rowIndex + 1), each off-diagonal pair is swapped exactly once. Diagonal elements matrix[rowIndex][rowIndex] are fixed points and remain unchanged.
  2. Step 2 β€” Reverse each row: After the transpose, each row contains the correct values but in reverse order. Reversing each row restores the proper left-to-right order, completing the 90Β° clockwise rotation.

This two-step algorithm runs fully in place and linearly with respect to the number of elements: each off-diagonal pair is swapped once during transpose, and every row is reversed once to finalize the rotation.

Time Complexity

O(nΒ²) β€” each element is visited once during the transpose and once during the row reversal.

Space Complexity

O(1) β€” the rotation is performed in place

Visucodize editorial solution titled JS Solution for LeetCode's Rotate Image coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/rotate-image.