Explorer
Data Structures & Algorithms

Rotate a 2D square matrix by 90 degrees clockwise in place.

Problem Statement

You are given an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise) in-place and return the rotated matrix.

Examples

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

Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Explanation: The matrix is rotated 90 degrees clockwise in-place.

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

Explanation: The matrix is rotated 90 degrees clockwise in-place.

Complexity

Time Complexity: O(N²)

Space Complexity: O(1)

Hints

💡 Hint 1: Rotating clockwise by 90 degrees equals transposing the matrix and then reversing each row. 💡 Hint 2: Transpose: swap matrix[i][j] with matrix[j][i] for all j > i. 💡 Hint 3: Row reversal: reverse each row matrix[i].

Editorial & Approach

Problem Overview & Intuition

A 90-degree clockwise rotation transforms element (i, j) to (j, n - 1 - i). This transformation is equivalent to matrix transposition followed by horizontal reflection (reversing each row).

Step-by-Step Approach

  1. Transpose the matrix: iterate i from 0 to n - 1, and j from i + 1 to n - 1, swapping matrix[i][j] and matrix[j][i].
  2. Reverse each row: for each row i, call matrix[i].reverse().
  3. Return matrix.

Optimal Implementation (JavaScript)

function rotateMatrix(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;
}

Complexity Analysis

Time Complexity O(N²) — transposing and reversing each cell.
Space Complexity O(1) — in-place rotation.

Edge Cases & Corner Traps Handled

  • 1x1 matrix: unchanged.
  • 2x2 matrix: immediate 4-way swap.

Rotate matrix by 90 degrees

Medium
You are given an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise) in-place and return the rotated matrix.
Example Scenarios
1Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Explanation:

The matrix is rotated 90 degrees clockwise in-place.

2Example 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]]
Explanation:

The matrix is rotated 90 degrees clockwise in-place.

Editor
Loading Editor...
matrix =
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:Click "Run" above to execute and verify your code here.
[[7,4,1],[8,5,2],[9,6,3]]