Skip to content

Rotate Image

Medium Day 10 • Striver Blind 75

Rotate an n x n 2D matrix 90 degrees clockwise in-place.

Example 1:

  • Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
  • Output: [[7,4,1],[8,5,2],[9,6,3]]

Constraints:

  • n == matrix.length
  • 1 <= n <= 20

Transpose matrix (swap matrix[i][j] with matrix[j][i]), then reverse each row.

Transpose + Reverse Rows


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
Start["Input Data"] --> Process["Process Element by Element"]
Process --> Lookup{"Hash Map / Set Lookup"}
Lookup -- "Match Found" --> Return["Return Indices / Result"]
Lookup -- "No Match" --> Store["Store in Map / Set"]
Store --> Process

function rotate(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) matrix[i].reverse();
return matrix;
}
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
  • Explanation: In-place transpose and row reverse.

function rotate(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) matrix[i].reverse();
return matrix;
}
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)
  • Explanation: Transpose matrix diagonally, then flip rows horizontally.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Rotate 90 deg clockwise = Transpose matrix + Reverse rows.


  1. Transpose then reverse each row.

👉 Solve this problem interactively in the DSA Lab