Start learning free

LESSON 290 OF 501 · MATRIX

Rotate Image in Python

Practice O(n^2)

Given a square matrix of integers matrix, with n rows and n columns, rotate it by 90 degrees clockwise: a quarter turn to the right, as you would turn a picture.

A matrix is a list of rows, and each row is a list of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right.

Rotate the matrix in place: move the numbers inside matrix itself, without building a second matrix. The function returns nothing; the output in the examples is matrix after the call.

 

Example 1:

Input: matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: [
  [7, 4, 1],
  [8, 5, 2],
  [9, 6, 3]
]
Explanation: The left column, read from the bottom up (7, 4, 1), becomes the top row, and the top row (1, 2, 3) becomes the right column.

Example 2:

Input: matrix = [
  [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]
]
Explanation: Every number moves a quarter turn around the center. The corners show it best: 5 goes to the top-right corner, 11 to the bottom-right, 16 to the bottom-left and 15 to the top-left.

Example 3:

Input: matrix = [
  [1, 2],
  [3, 4]
]
Output: [
  [3, 1],
  [4, 2]
]
Explanation: Each number moves one corner clockwise: 1 to the top-right, 2 to the bottom-right, 4 to the bottom-left and 3 to the top-left.

 

Constraints:

  • matrix has n rows and every row has n values, with 1 <= n <= 500.
  • Every value is an integer between -1000 and 1000; values can be negative and can repeat.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 6
    Ctrl + Enter to check

    Rotate Image in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free