Show problems as
Classic problem #48MediumArrayMathMatrix

Rotate Image

Real-world version: Wafer Quarter Turn
Tracked in this browser only
Read Rotate Image on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

An inspection rig stores one calibration offset per die of a wafer in grid, a square board of n rows by n columns. Offsets are signed: a die can read below the reference as easily as above it.

The wafer has just been remounted a quarter turn clockwise, so the stored board no longer lines up with the hardware. Turn the board itself a quarter turn clockwise: the row that was on top must end up as the rightmost column, read downwards, and so on around the board.

The rig has no spare memory for a second board of this size, so you must shuffle the values inside grid where they already sit rather than filling in a freshly allocated board and handing that back. Only a fixed number of scratch values is allowed, no matter how large n is. After rearranging grid, return grid.

Boards that are not square are outside the scope of this task, so you may assume every row is exactly as long as the number of rows.

Examples

Example 1

Input
grid = [[3, -7], [12, 0]]
Output
[[12, 3], [0, -7]]

The left column 3, 12 becomes the top row read upwards, so 12 lands first and 3 follows.

Example 2

Input
grid = [[2, 5, -1], [0, 9, 4], [-6, 3, 8]]
Output
[[-6, 0, 2], [3, 9, 5], [8, 4, -1]]

Each column, read from the bottom up, becomes a row of the turned board. The centre die never moves.

Example 3

Input
grid = [[4]]
Output
[[4]]

A single die is its own row and column, so a quarter turn leaves the board as it was.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 20
  • -1000 <= grid[i][j] <= 1000
  • Only a fixed amount of extra space may be used; no second board of size n by n

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def quarter_turn(grid: list[list[int]]) -> list[list[int]]:
Java
public int[][] quarterTurn(int[][] grid)