Rotate Image

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    Given an n × n matrix, rotate it 90 degrees clockwise in place. You must change the input matrix directly; allocating a second n × n matrix is not allowed.

    A short problem that shows how carefully you handle indices. Interviewers like it because there is a neat two-step trick, and because the "obvious" in-place code has two classic bugs. Original problem: LeetCode 48.

    Example

    After a clockwise quarter turn, the top row 1, 2, 3, 4 reads down the right-hand column.
    After a clockwise quarter turn, the top row 1, 2, 3, 4 reads down the right-hand column.
    Input:  [[ 1,  2,  3,  4],
             [ 5,  6,  7,  8],
             [ 9, 10, 11, 12],
             [13, 14, 15, 16]]
    Output: [[13,  9,  5,  1],
             [14, 10,  6,  2],
             [15, 11,  7,  3],
             [16, 12,  8,  4]]
    Input:  [[7, 3],
             [1, 9]]
    Output: [[1, 7],
             [9, 3]]

    Constraints (assumed)

    • 1 ≤ n ≤ 1,000.
    • Values are integers (the type doesn't matter: only positions move).

    What this question tests

    • Working out where each cell goes: m[i][j] moves to m[j][n − 1 − i].
    • Doing it in place with O(1) extra memory, which rules out the copy-and-fill answer.
    • Getting loop bounds right so each cell moves exactly once.

    Questions to ask first

    1. Clockwise or counter-clockwise? (Here: clockwise.)
    2. Is the matrix always square? A non-square matrix can't be rotated in place because its shape changes. (Here: square.)
    3. Must it be in place, or may I return a new matrix? (Here: in place.)
    4. Is n possibly 1 or odd? Odd sizes have a centre cell that never moves.