Ctrl K

Turn a Square Clockwise

Medium
You are given a square table grid of size n×n, say the pixels of a picture. Turn it 90° clockwise. Return the turned table. Try to do the turn in place: change grid itself without allocating a second table.
Example 1
grid=[[1, 2], [3, 4]] → [[3, 1], [4, 2]]

After a clockwise turn the left column, read bottom to top, becomes the top row: [[3, 1], [4, 2]].

Example 2
grid=[[0, -1, 2], [3, 4, 5], [6, 7, 8]] → [[6, 3, 0], [7, 4, -1], [8, 5, 2]]

The result is [[6, 3, 0], [7, 4, -1], [8, 5, 2]]; the center cell 4 stays put.

Example 3
grid=[[7]] → [[7]]

A 1×1 table does not change when turned.

Constraints
  • 1 ≤ n ≤ 20
  • grid has n rows of n numbers each
  • -1000 ≤ grid[i][j] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFour-Corner Rectangles MediumMagic 3×3 Blocks MediumThree Heaviest Diamonds MediumLevel the Grid in Steps MediumAlarm Beams Between Rows Medium
loading Python…
Input
grid=[[1, 2], [3, 4]]
Expected
[[3, 1], [4, 2]]

Run checks the first 3 tests in your browser. Submit checks all 35 tests on the server, hidden ones included.