TRT
Sign in
mediumFoundationsLeetCode#index mapping#transpose and reverse

Rotate image

Rotate an n × n matrix by 90 degrees clockwise, in place, using index arithmetic.

The Runtime Theory Team1 min read
Taught inIndex arithmeticAn array index is an offset into a block of memory. The same arithmetic flattens grids, finds neighbors, wraps around the end and turns a position back into a row and column.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

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

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

inmatrix = [[1,2],[3,4]]

out[[3,1],[4,2]]

inmatrix = [[1]]

out[[1]]

Given an n × n matrix, rotate it 90 degrees clockwise. Modify the matrix itself; don't allocate another one.

Before you code

Work out where one cell goes. In a clockwise rotation, the cell at row r, column c moves to row c, column n − 1 − r. Check it on the corner (0, 0) of a 3 × 3 matrix: it moves to (0, 2), the top right.

Hints

  1. A rotation is two simpler moves: transpose (swap [r][c] with [c][r]), then reverse each row.
  2. When transposing in place, only swap cells above the diagonal (c > r), or every pair gets swapped twice and nothing changes.
  3. Alternative: rotate four cells at a time, from (r, c) to (c, n−1−r) to (n−1−r, n−1−c) to (n−1−c, r), working ring by ring from the outside.

Production & complexity notes

When solving Rotate image on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Index arithmetic to reinforce the underlying pattern.

What it practices

Mapping positions with index arithmetic, from Index arithmetic.

Not started

Sign in to save your learning progress.

Sign in to save