Turn the Grid by Quarter Turns
EasyMatrix
Problem
A label printer receives an m × n bitmap grid and an instruction to rotate it turns times by 90 degrees clockwise. The bitmap is not necessarily square, so each quarter turn swaps its height and width.
Return the rotated bitmap as a new grid. turns can be very large.
Example 1
- Input:
- grid = [[1, 2, 3], [4, 5, 6]], turns = 1
- Output:
- [[4, 1], [5, 2], [6, 3]]
The bottom-left value 4 becomes the top-left; the 2 × 3 grid becomes 3 × 2.
Example 2
- Input:
- grid = [[1, 2, 3], [4, 5, 6]], turns = 2
- Output:
- [[6, 5, 4], [3, 2, 1]]
Example 3
- Input:
- grid = [[1, 2, 3], [4, 5, 6]], turns = 4
- Output:
- [[1, 2, 3], [4, 5, 6]]
Four quarter turns are a full turn.
Constraints
- 1 ≤ m, n ≤ 200
- 0 ≤ turns ≤ 10^9
- -1000 ≤ grid[i][j] ≤ 1000
Hint
Show the first hint
Rotating four times returns the original grid. What does that tell you about a huge turns value?
Walkthrough
How to approach it
01Clarify before coding
- Clockwise? Yes, every turn is 90 degrees clockwise.
- Can turns be 0? Yes: return the grid unchanged.
- Is the grid square? Not necessarily, so the shape alternates between m × n and n × m.
02Brute force
Apply a quarter turn literally turns times.
Cost: O(turns · m · n): with turns up to 10^9 this never finishes.
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.