All problems
0048MediumArrayMathMatrix

Wafer Quarter Turn

Tracked in this browser only
Write code

Trains the technique from

LeetCode 48Rotate Image

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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