Quarter-Turn the Photo
MediumMatrix
Problem
A photo editor stores a square image as an n × n grid of pixel values. Rotate the image 90 degrees clockwise, modifying grid in place.
Do not allocate a second n × n grid; O(1) extra memory is expected. The function returns nothing.
Example 1
- Input:
- grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Output:
- [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
The left column 1, 4, 7 read from the bottom becomes the top row 7, 4, 1.
Example 2
- Input:
- grid = [[1, 2], [3, 4]]
- Output:
- [[3, 1], [4, 2]]
Constraints
- 1 ≤ n ≤ 500
- -1000 ≤ grid[i][j] ≤ 1000
Hint
Show the first hint
Where does the pixel at (r, c) end up after a clockwise quarter turn?
Walkthrough
How to approach it
01Clarify before coding
- Clockwise or counter-clockwise? Clockwise.
- Is the grid always square? Yes, which is what makes an in-place rotation possible.
- Can I build a new grid and copy it back? No, O(1) extra memory.
02Brute force
Allocate a new grid and write out[c][n - 1 - r] = grid[r][c] for every cell, then copy it back.
Cost: O(n²) time and O(n²) extra memory, which breaks the in-place requirement.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.