787. Rotate a square image 90 degrees clockwise in place
On a device with tight memory, you may not be allowed to allocate a second copy of an image buffer. Rotating a camera frame then has to happen in place.
Write rotate_in_place(img). img is an n x n list of lists of pixel values. Rotate it 90 degrees clockwise by changing img itself, using only O(1) extra memory beyond a few variables. Return the same list object you were given.
An empty image [] is returned as it is.
def rotate_in_place(img)Example 1
for img = [[1, 2], [3, 4]], rotate_in_place(img) returns [[3, 1], [4, 2]], and img itself now holds [[3, 1], [4, 2]].
Example 2
Input: img = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Constraints
- 0 <= n <= 1,000
- img is square
Hint 1
Write down where (i, j) goes after a clockwise turn.
Hint 2
A transpose plus a row reverse is the same map.
Hint 3
Mutate rows, do not replace them.
Common mistakes
- Swapping every pair in the transpose, which undoes it.
- Reversing columns instead of rows, which rotates counterclockwise.
- Returning a new matrix instead of changing the input.
Understand the idea
In-place array work means rearranging data inside the buffer you already have. For rotation, transpose plus row reversal is the cleanest route: [[1, 2], [3, 4]] transposes to [[1, 3], [2, 4]], and reversing each row gives [[3, 1], [4, 2]]. The other classic way rotates four cells at a time in rings. On memory-limited hardware, in-place transforms avoid a second allocation the size of the frame.