Rotate Image Medium 0 attempts
LeetCode ↗

Rotate Image

Medium MatrixBFSDFS LeetCode

You're given an n × n matrix of integers representing an image. Rotate it 90 degrees clockwise, modifying the matrix in place — allocating a second n × n matrix for the output isn't allowed, though a few extra scalar variables are fine.

As a sanity check: after rotating, the original first row becomes the new last column, and the same pattern continues for every row.

Input Format
Implement rotate(matrix). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Modify argument 1 in place. The editor compares its final value; the function return value is ignored.

Sample Input and Output

Example 1 · Run Sample

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 = [[1]]
Output
[[1]]
Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000
Test Cases (2)
Case 1
Args: [[[1,2,3],[4,5,6],[7,8,9]]] Expected: [[7,4,1],[8,5,2],[9,6,3]]
Case 2
Args: [[[1]]] Expected: [[1]]
Topics

Transpose + Reverse Rows

javascript
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 (const row of matrix) row.reverse();
}

Time: O(n²) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript