Start learning free

LESSON 331 OF 671 · MATRIX

Rotate Image in JavaScript: In Place with Transpose and Reverse

Practice O(n^2) Read the full explanation

You get a square grid matrix of integers, with n rows and n columns.

Rotate it a quarter turn clockwise, like turning a photo onto its right side.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

Work in place. Change the numbers inside matrix itself, and don't fill a new grid.

Your function returns nothing. Each example's output shows matrix after the function runs.

 

Example 1:

Input: matrix = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 6]
]
Output: [
  [8, 3, 4],
  [1, 5, 9],
  [6, 7, 2]
]
Explanation: The left column, read from the bottom up, is now the top row.
The top row is now the right column.
The 5 in the center stays where it is.

Example 2:

Input: matrix = [
  [-3, 8],
  [8, 0]
]
Output: [
  [8, -3],
  [0, 8]
]
Explanation: Each number moves to the next corner clockwise:
-3 goes to the top right,
the top-right 8 goes to the bottom right,
0 goes to the bottom left,
the bottom-left 8 goes to the top left.

Example 3:

Input: matrix = [
  [7]
]
Output: [
  [7]
]
Explanation: A single number has nowhere to move.

 

Constraints:

  • n is from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · MATRIX

    Rotate Image in JavaScript, explained

    Problem overview

    The method rotate(matrix) receives a square matrix: an array of n rows, each an array of n integers. It must turn the matrix a quarter turn clockwise, like turning a picture to the right. It returns nothing. The rotation happens inside matrix itself, with no second matrix, and the statement asks for O(n²) time and O(1) extra space.

    For the 3 by 3 matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the result is [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. The left column, read from the bottom up, becomes the top row, and the top row becomes the right column.

    Approach: two flips make a turn

    The easy way to rotate is to build a new matrix and copy every number to its new place: the value at row i, column j goes to row j, column n - 1 - i. That takes O(n²) extra space, which the statement rules out. Moving each cell directly in four-cell cycles also works, but the index arithmetic is easy to get wrong.

    A simpler way combines two easy flips:

    1. Transpose the matrix: flip it over its main diagonal, the line from the top-left corner to the bottom-right one. The number in row i, column j trades places with the number in row j, column i. Every row becomes the column with the same number.
    2. Reverse every row. After the transpose, row i holds the old column i from top to bottom. A clockwise turn needs it from bottom to top, so each row is read backwards.

    Both flips only swap numbers inside the matrix, so no extra space is needed beyond a few variables. On the 3 by 3 example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]], and reversing each row gives the answer [[7, 4, 1], [8, 5, 2], [9, 6, 3]].

    Step by step

    1. Store the size matrix.length in n. The matrix is square, so it is both the row count and the column count.
    2. Loop over the rows with i from 0 to n - 1 for the transpose.
    3. Loop over the columns to the right of the diagonal: j starts at i + 1. Each pair of mirrored cells is visited once. If j started at 0, every pair would be swapped twice, and the second swap would undo the first.
    4. Swap matrix[i][j] and matrix[j][i] with array destructuring, which needs no temporary variable.
    5. Loop over the rows again, now to reverse each one.
    6. Reverse matrix[i] in place with reverse().

    The solution in JavaScript

    class Solution {
        rotate(matrix) {
            let n = matrix.length;
            for (let i = 0; i < n; i++) {
                for (let j = i + 1; j < n; j++) {
                    [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
                }
            }
            for (let i = 0; i < n; i++) {
                matrix[i].reverse();
            }
        }
    }
    

    Some JavaScript details worth knowing:

    • Destructuring swap. The right-hand side [matrix[j][i], matrix[i][j]] is evaluated first, building a new two-element array from both old values. The left-hand side then unpacks it into the two cells. Because the old values are already copied, no temporary variable is needed. A line before it that doesn't end in a semicolon could make JavaScript read the [ as an index into the previous expression, so end the previous statement with ;.
    • reverse() works in place. It changes the array it is called on and also returns that same array (r.reverse() === r is true). Since each row is an object inside matrix, reversing it changes matrix. Nothing needs to be returned or assigned back.
    • Rows are references. A matrix in JavaScript is an array of arrays, so matrix[i] is the row object itself. That is why an in-place function sees its changes reflected in the caller's matrix. Assigning a new array to the parameter, such as matrix = [[9]] inside the function, only changes the local variable, and the caller's matrix stays as it was.
    • No return value. rotate has no return statement, so a call evaluates to undefined. The lesson's tests check matrix after the call.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the row reversals touch every cell once. Both are proportional to n², the number of values in the matrix, so no solution can do better than O(n²).

    Space: O(1) extra. The swaps use no new arrays beyond the temporary pair that destructuring creates, which is a constant size. The matrix is changed where it stands.

    Edge cases and common mistakes

    • A 1 by 1 matrix. [[7]] stays [[7]]: the inner loop never runs, and reversing a single-element row changes nothing.
    • Swapping every pair twice. With j starting at 0, the loops visit both (i, j) and (j, i), and the second swap undoes the first. For [[1, 2], [3, 4]] the matrix ends up unchanged after the transpose step.
    • Reversing the wrong thing. Transpose then reverse each row turns the matrix clockwise. Reversing the order of the rows instead of each row's contents would give a counterclockwise turn.
    • Building a new matrix and returning it. The lesson's tests look at matrix itself, so a new array that you return would be ignored.
    • Creating rows with fill. If you build a matrix yourself with new Array(2).fill([0, 0]), every row is the same array. Setting sh[0][0] = 5 then shows up in both rows: [[5, 0], [5, 0]]. Use Array.from or a loop to create separate rows.
    • Negative values and duplicates. The swaps move values without comparing them, so negative numbers and repeated numbers need no special handling.

    Testing

    • [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]].
    • [[7]] stays [[7]].
    • [[1, -1], [-2, 2]] becomes [[-2, 1], [2, -1]].
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free