← DiffPush

Rotate matrix

Standard Bar Arrays · Medium O(n^2) · O(1)

Rotating a Frame Buffer in Place

A camera pipeline holds one square frame in a fixed memory buffer and must present it turned a quarter turn clockwise. There is no spare buffer available at that moment, so the pixel grid must be rewritten in place. After the rewrite, column order and row order both shift as the image turns.

Input: An n x n matrix of integers representing the current frame.

Output: The same matrix rotated 90 degrees clockwise, modified in place.

Constraints

Examples

Example 1

Input: {"matrix":[[1,2,3],[4,5,6],[7,8,9]]}
Output: [[7,4,1],[8,5,2],[9,6,3]]
The bottom-left corner 7 travels to the top-left, and the rest follow the same quarter-turn mapping.

Example 2

Input: {"matrix":[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]}
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
The 4x4 frame turns as a whole, so the last row of the input becomes the first column of the output.

Solve this in your browser →

Also on LeetCode ↗