InterviewPrepKit

Home / Coding / Math & Geometry

Rotate Image

medium Original ↗
Solving tips
  • Recall the cleanest in-place trick: transpose the matrix, then reverse each row, which equals a 90-degree clockwise rotation.
  • Key mapping: cell (i,j) lands at (j, n-1-i); the transpose-then-reverse decomposition realizes it without a copy.
  • Target O(n^2) time and O(1) extra space, since the in-place requirement is the whole point.
  • Common pitfall: in the transpose loop start j at i+1 (not 0), otherwise every pair swaps twice and you get the original back; and reverse rows AFTER transpose or you rotate the wrong way.

Problem

You are given an n x n 2-D matrix representing an image. Rotate the image by 90 degrees clockwise.

You must rotate it in place — modify the input matrix directly and do not allocate another n x n matrix to hold the result. Return nothing; the caller reads the mutated input.

Examples

  • matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]] — the top row 1,2,3 becomes the right column top-to-bottom.
  • matrix = [[1,2],[3,4]][[3,1],[4,2]] — a 2×2 rotates so 3 moves to the top-left.
  • matrix = [[5]][[5]] — a single cell is unchanged.

Constraints

  • n == len(matrix) == len(matrix[i])
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000
  • The interesting requirement is O(1) extra space: rotate by rearranging the existing cells, not by building a copy.

Think about it first

Hint 1 Where does the cell at row `i`, column `j` land after a clockwise 90° turn? Work it out on the 3×3 example: it moves to row `j`, column `n-1-i`.
Hint 2 A clockwise rotation equals two simpler operations you can each do in place: first **transpose** the matrix (swap across the main diagonal), then **reverse each row**. Try it on the 3×3 example.
Hint 3 Alternatively, rotate the matrix one concentric ring at a time. Within a ring, move four cells in a single 4-way cyclic swap, using just one temporary variable, and walk offsets around the ring.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.