‹ DS&A interview · Socratic
DSA · Matrix · #155

Rotate Image

Module 63 · difficulty 3/5·30:00starts on first keystroke

Given an `n x n` 2D `matrix` representing an image, rotate the image by **90 degrees clockwise**, **in place**. You must modify the input matrix directly — do **not** allocate another 2D matrix to perform the rotation. The function returns nothing (`undefined`); the rotation must be reflected in the passed-in `matrix`. Implement `rotate(matrix)`.

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.
  • matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
  • matrix = [[1]] [[1]]A single element is unchanged.
Constraints
  • · n == matrix.length == matrix[i].length
  • · 1 <= n <= 20
  • · -1000 <= matrix[i][j] <= 1000
  • · Rotation must be performed in place with O(1) extra space.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.