v9.1.1
Menu

Rotate Image

mediumPROMath & GeometryUber DSA

Rotate an n x n 2D matrix 90 degrees clockwise in-place.

Input: matrix, a list of n lists of n integers (the example shows it as rows of comma-separated integers). Modify matrix in place and return nothing; the tests print the rotated matrix afterwards, one row per line with values separated by spaces.

Example

Input
1,2,3
4,5,6
7,8,9
Output
7 4 1
8 5 2
9 6 3
Reasoning
  • matrix is a square grid with n=3n = 3 rows and 3 columns: rows 1,2,3, 4,5,6, 7,8,9. Count rows and columns from 0.
  • A 90° clockwise turn sends the entry at row ii, column jj to row jj, column n−1−in - 1 - i. Here that column is 2−i2 - i.
  • Track the top row: 1 at (0,0)(0,0) lands at (0,2)(0,2), 2 at (0,1)(0,1) lands at (1,2)(1,2), 3 at (0,2)(0,2) lands at (2,2)(2,2). The top row becomes the right column.
  • Track the left column: 7 at (2,0)(2,0) lands at (0,0)(0,0) and 4 at (1,0)(1,0) lands at (0,1)(0,1), so the new top row is 7 4 1. Every other cell follows the same rule, giving 8 5 2 and 9 6 3 below it.
  • Notice that the four corners trade places in a cycle (1→3→9→7→11 \to 3 \to 9 \to 7 \to 1 by position), and the centre 5 stays put because (1,1)(1,1) maps to itself.
  • The grid itself must hold the rotated values; the printed rows are read from it.

Constraints

  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

More from Uber DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.