You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
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]]
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a square picture made of a grid of tiny colored squares that you need to turn sideways by a quarter turn. The brute force strategy involves grabbing a brand new, empty canvas and systematically copying every single piece of the picture over to its new rotated home one by one.
Here's how the algorithm would work step-by-step:
def rotate(matrix):
matrix_dimension = len(matrix)
# Initialize a new canvas with zeros to safely build the rotated version without data corruption
rotated_canvas = [[0 for column_index in range(matrix_dimension)] for row_index in range(matrix_dimension)]
for original_row_index in range(matrix_dimension):
for original_column_index in range(matrix_dimension):
# Calculate the new column position from the right so rows map correctly to columns
target_column_index = matrix_dimension - 1 - original_row_index
target_row_index = original_column_index
rotated_canvas[target_row_index][target_column_index] = matrix[original_row_index][original_column_index]
# Copy every element back into the original matrix reference to satisfy in-place requirements
for row_index in range(matrix_dimension):
for column_index in range(matrix_dimension):
matrix[row_index][column_index] = rotated_canvas[row_index][column_index]Instead of trying to move every single piece to its final destination all at once, which gets very messy, we can achieve the same rotation by performing two simple physical flips. This clever shortcut lets us rearrange everything neatly in place without needing extra space.
Here's how the algorithm would work step-by-step:
def rotate(matrix):
matrix_dimension = len(matrix)
# Flipping upside down prepares the rows to become columns in their correct inverted order.
for row_index in range(matrix_dimension // 2):
for column_index in range(matrix_dimension):
matrix[row_index][column_index], matrix[matrix_dimension - 1 - row_index][column_index] = matrix[matrix_dimension - 1 - row_index][column_index], matrix[row_index][column_index]
# Transposing across the diagonal completes the 90-degree clockwise rotation efficiently in place.
for row_index in range(matrix_dimension):
for column_index in range(row_index + 1, matrix_dimension):
matrix[row_index][column_index], matrix[column_index][row_index] = matrix[column_index][row_index], matrix[row_index][column_index]| Case | How to Handle |
|---|---|
| Empty or null matrix input | Check for null or empty references at the start to immediately return without throwing runtime exceptions. |
| Minimum sized 1x1 matrix | The algorithm skips rotation loops since layers are non-existent, leaving the single element correctly untouched. |
| 2x2 matrix minimum multi-element case | The outer and inner loop bounds correctly process the single four-element quadrant swap without out of bounds errors. |
| Large scale matrices up to maximum constraints | The in-place O(1) extra space transpose and reverse approach avoids memory limit issues while running in optimal O(N squared) time. |
| Matrix containing all identical values | Swapping identical values produces no visible change but executes the index math safely without data corruption. |
| Matrix with extreme values like negatives and zeros | Since the approach relies purely on index swapping rather than arithmetic operations, any integer value is handled uniformly. |
| Odd versus even dimensions of n by n matrix | Adjusting the layer boundaries for outer and inner loops correctly handles the exact center element in odd dimensions. |
| Memory constraint limits with in-place requirement | Mutating the original 2D array directly satisfies the strict O(1) auxiliary space requirement without allocating auxiliary grids. |