Rotate Image

Try to solve the Rotate Image problem.

Statement#

Given an n×nn \times n matrix, rotate the matrix 90 degrees clockwise. The performed rotation should be in place, i.e., the given matrix is modified directly without allocating another matrix.

Note: The function should only return the modified input matrix.

Constraints:

  • matrix.length == matrix[i].length
  • 11 \leq matrix.length 20\leq 20
  • 103-10^3 \leq matrix[i][j] 103\leq 10^3

Examples#

Created with Fabric.js 3.6.6 Sample Example 1 ------------------------------------------

1 of 3

Created with Fabric.js 3.6.6 Sample Example 2 ------------------------------------------

2 of 3

Created with Fabric.js 3.6.6 Sample Example 3 ------------------------------------------

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Rotate Image

1

What is the output if the following matrix is given as input?

matrix = [[2, 6, 8],
                  [3, 4, 8],
                  [9, 8, 8]]

A)

[[8, 8, 9],
  [8, 4, 3],
  [8, 6, 2]]

B)

[[8, 8, 8],
  [6, 4, 8],
  [2, 3, 9]]

C)

[[9, 3, 2],
  [8, 4, 6],
  [8, 8, 8]]

D)

[[8, 8, 9],
  [8, 6, 2],
  [8, 4, 3]]

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Traverse groups of four cells in the matrix, starting from the four corners.

Swap the top-left cell with the top-right cell.

Swap the top-left cell with the bottom-right cell.

Swap the top-left cell with the bottom-left cell.

Move to the next group of four cells, and repeat the above steps.


Try it yourself#

Implement your solution in the following coding playground:

Python
usercode > main.py
Input #1
Rotate Image

Solution: Set Matrix Zeros

Solution: Rotate Image