Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in TypeScript: 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

    TYPESCRIPT · MATRIX

    Rotate Image in TypeScript, explained

    Problem overview

    The method rotate receives a square matrix, matrix, an array of n rows with n numbers each. It must turn the matrix a quarter turn clockwise, in place: the numbers move inside matrix itself, nothing is returned, and no second matrix is built. The time budget is O(n²), which is the number of cells, with O(1) extra space.

    For this input:

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

    the matrix afterwards is:

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

    The left column read from the bottom up (7, 4, 1) becomes the top row, and the top row becomes the right column.

    Approach: two simple flips make a turn

    Building a rotated copy is easy: the number at row i, column j goes to row j, column n - 1 - i. But the lesson wants the move done inside the same matrix, and rotating cell by cell in place means juggling four cells at a time.

    A quarter turn clockwise is the same as two flips, one after the other:

    1. Transpose: mirror the matrix over its main diagonal, the line from the top-left corner to the bottom-right. The number at row i, column j swaps places with the one at row j, column i. Row i becomes what column i was.
    2. Reverse every row.

    On the example, the transpose gives rows [1, 4, 7], [2, 5, 8], [3, 6, 9]. After the transpose, row i holds the old column i from top to bottom, but a clockwise turn needs it from bottom to top. Reversing each row gives [7, 4, 1], [8, 5, 2], [9, 6, 3], which is the answer. Both flips only swap numbers inside the matrix, so the extra space stays constant.

    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 to start 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 for the second flip.
    6. Call reverse() on matrix[i]. It reverses the array where it is, so the row inside matrix changes.

    The solution in TypeScript

    class Solution {
        rotate(matrix: number[][]): void {
            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 TypeScript details:

    • The destructuring swap. The right side, [matrix[j][i], matrix[i][j]], is evaluated first and creates a small array holding both old values. The left side then unpacks that array into the two cells in the other order. A temporary array is created on each swap, but it is a constant-size detail, not storage that grows with the matrix.
    • The semicolon before the swap matters in general. A line that starts with [ can be read as a continuation of the previous line. Here the previous line ends with {, so it is safe, but after an expression statement without a semicolon the line would be parsed as an index access.
    • void and in-place work. The return type void says the method gives back nothing. The caller sees the result through the same matrix array, because arrays are passed by reference: the method changes the caller's rows, not a copy.
    • reverse() mutates. Unlike map or slice, which return new arrays, reverse() reverses the array it is called on and also returns it. Here the returned value is ignored.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the row reversals touch each cell once more. Both are proportional to the number of cells.

    Space: O(1) extra. Only n, the loop counters and the tiny array of each swap are used. The matrix itself is rearranged.

    Edge cases and common mistakes

    • Inner loop starting at 0. Every pair gets swapped twice and the matrix is unchanged by the transpose. For [[1, 2], [3, 4]] the matrix comes out as [[1, 2], [3, 4]] after this double swap.
    • Doing the flips in the wrong combination. Transpose then reverse each row is a clockwise turn. Reversing the order of the rows after a transpose would turn the matrix counterclockwise instead.
    • The smallest matrix. A 1 by 1 matrix has no pair to swap and reversing a one-element row changes nothing, so [[7]] stays [[7]].
    • Building a new matrix. Assigning a freshly built array to the parameter, such as matrix = ..., changes only the local variable and leaves the caller's matrix untouched.
    • Even and odd sizes. The two-flip method handles both without special cases, including the center cell of an odd matrix, which the diagonal loop never moves.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]].
    • [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
    • [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] becomes [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]].
    • [[7]] stays [[7]].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free