Rotate Image
Explore how to rotate an n by n matrix 90 degrees clockwise in place, modifying the original matrix without extra memory. This lesson helps you understand matrix traversal and in-place transformations, key skills for technical coding interviews.
We'll cover the following...
Statement
Given an 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.lengthmatrix[i].length-
matrix.length -
matrix[i][j]
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
What is the output if the following matrix is given as input?
matrix = [[2, 6, 8],
[3, 4, 8],
[9, 8, 8]]
[[8, 8, 9],
[8, 4, 3],
[8, 6, 2]]
[[8, 8, 8],
[6, 4, 8],
[2, 3, 9]]
[[9, 3, 2],
[8, 4, 6],
[8, 8, 8]]
[[8, 8, 9],
[8, 6, 2],
[8, 4, 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.
Try it yourself
Implement your solution in the following coding playground:
import java.util.*;public class RotateImage {public static int[][] rotateImage(int[][] matrix) {// Replace this placeholder return statement with your codereturn matrix;}}