~/problems / Math & matrices

Rotate Image

medium ~25 min

A square image is stored as an n x n grid of pixel values. Write rotate_clockwise(grid) that turns the image 90 degrees clockwise, changing grid in place. It returns None; the caller looks at the mutated grid.

After the turn, the old top row becomes the new right column, the old left column becomes the new top row, and so on.

g = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
rotate_clockwise(g)
g   # [[7, 4, 1],
    #  [8, 5, 2],
    #  [9, 6, 3]]

g = [[1, 2],
     [3, 4]]
rotate_clockwise(g)
g   # [[3, 1],
    #  [4, 2]]
  • 1 <= n <= 500; values are in [-1000, 1000].
  • Don't build a second n x n grid and copy it back: move the values around inside grid itself.
  • Aim for O(n²) time and O(1) extra space.
Show hint

a quarter turn can be written as two simpler rearrangements that each just swap pairs of cells. Try flipping the grid across one of its diagonals and see what's left to do.

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc