I encountered a matrix rotation coding problem that started with the classic task of rotating an n × n matrix 90 degrees clockwise in place. The interviewer then introduced two follow-ups: handling rectangular matrices and generalizing the rotation to different angles or counterclockwise directions.
The core problem was equivalent to LeetCode 48, but the follow-ups required a deeper understanding of index transformations and memory constraints. The most important requirement was that the original square matrix had to be modified directly without allocating another matrix of the same size.
Interview Details
Coding — Rotate a Matrix 90 Degrees Clockwise In Place
Problem Description
Given an n × n integer matrix, rotate the matrix 90 degrees clockwise. The rotation must be performed in place, meaning the input matrix itself must be modified. Allocating a separate n × n output matrix is not allowed. The algorithm should use constant auxiliary space.
The straightforward approach is to allocate a new matrix and copy each element to its rotated position. For a clockwise rotation, an element at position (row, col) moves to (col, n - 1 - row). The transformation can be expressed as: newMatrix[col][n - 1 - row] = matrix[row][col]
An implementation would look like:
defrotateWithExtraSpace(matrix): n =len(matrix) result =[[0]* n for _ inrange(n)]for row inrange(n):for col inrange(n): result[col][n -1- row]= matrix[row][col]return result
defrotateWithExtraSpace(matrix): n =len(matrix) result =[[0]* n for _ inrange(n)]for row inrange(n):for col inrange(n): result[col][n -1- row]= matrix[row][col]return result
Although this approach is straightforward, it requires O(n²) additional space and doesn't satisfy the in-place requirement.
Optimized Approach — Transpose and Reverse
The standard in-place solution consists of two transformations.
First, transpose the matrix by swapping elements across its main diagonal. Then reverse every row horizontally to obtain the 90-degree clockwise rotation.
The implementation is:
defrotate(matrix): n =len(matrix)# Step 1: Transposefor i inrange(n):for j inrange(i +1, n): matrix[i][j], matrix[j][i]
defrotate(matrix): n =len(matrix)# Step 1: Transposefor i inrange(n):for j inrange(i +1, n): matrix[i][j], matrix[j][i]
Unlock Full Details
Create a free account to unlock this interview experience report.