Search⌘ K
AI Features

Rotate Image

Understand how to rotate a square matrix 90 degrees clockwise in place by modifying the given matrix without extra allocation. Learn matrix traversal and transformation strategies, and implement your solution efficiently within set constraints.

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

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]]


1 / 3

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.

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

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > RotateImage.java
import java.util.*;
public class RotateImage {
public static int[][] rotateImage(int[][] matrix) {
// Replace this placeholder return statement with your code
return matrix;
}
}
Rotate Image