InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Rotate Image

medium Original ↗ 00:00

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
  • O(1) extra space: rearrange the existing cells rather than 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug