KatInterview

Quarter-Turn a Square Grid of Pixels Without Extra Storage

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingmatrixin-placesimulation

Last updated

Turn a square integer grid a quarter turn clockwise by modifying it in place, testing index mapping and in-place transforms such as transpose plus row reversal.

You are given a square grid of integers with n rows and n columns, where each cell holds a pixel value. Turn the grid a quarter turn (90 degrees) clockwise.

The rotation must be done in place: change the cells of the grid you were given, and do not build a second n x n grid to hold the result. After the rotation, return the same grid object.

Under a clockwise quarter turn, the value at row r, column c of the original grid ends up at row c, column n - 1 - r. The first row of the original becomes the last column of the result, the second row becomes the second-to-last column, and so on.

Input

  • grid: a list of n lists, each containing n integers.

Output

  • The rotated grid, as a list of lists of integers. This is the same object that was passed in, modified in place.

Constraints

  • grid is square: len(grid) == len(grid[i]) == n for every row i
  • 1 <= n <= 500
  • -1000 <= grid[i][j] <= 1000
  • Values may repeat, and may be negative
  • A 1 x 1 grid is returned unchanged

Examples

Example 1

Input: rotate_grid_clockwise([[1, 2], [3, 4]])

Output: [[3, 1], [4, 2]]

Example 2

Input: rotate_grid_clockwise([[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]]

Hints

Hint 1

Work out where a single cell goes. The cell at (r, c) must end at (c, n - 1 - r). Check this on the 2 x 2 case by hand.

Hint 2

Try splitting the quarter turn into two simpler in-place moves. One of them swaps cells across the main diagonal.

Hint 3

After swapping across the main diagonal, each row still needs one more fix. Think about what happens to column positions when you reverse a row. Be careful to swap each off-diagonal pair only once.