DSA Tracker

Medium

Rotate Image

A medium Matrix problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Matrix
Sheets
2
Core for
10 roles
Platform
LeetCode

The problem

Given an n-by-n matrix, rotate it 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]]
Why
The matrix is rotated 90 degrees clockwise. The first column becomes the first row reversed, and so on.

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].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

How to think about it

Updated 2026-09-09

A 90-degree clockwise rotation maps position (i,j) to (j, n-1-i). This is two simpler operations composed: transpose across the diagonal, then reverse each row. Neither needs extra memory beyond a swap variable.

Approaches, worst first

  1. Create a new rotated matrix

    time O(n^2) · space O(n^2)

    Allocate a fresh n-by-n matrix. Place each element from position (i,j) into position (j, n-1-i) of the new one. Correct but violates the in-place requirement and uses O(n^2) extra space, which is the whole point of the problem.

  2. Transpose then reverse each rowWrite this one

    time O(n^2) · space O(1)

    First swap matrix[i][j] with matrix[j][i] for all i < j, reflecting across the main diagonal. Then reverse each row. Together these two operations produce a 90-degree clockwise rotation using only swap variables.

Where people lose marks · 3
  • When transposing, you must swap only the upper triangle where j > i. Swapping the entire matrix including the diagonal undoes each swap and restores the original matrix.
  • Forgetting to reverse each row after transposing produces a counter-clockwise rotation, not clockwise. The transpose alone reflects across the diagonal, which is the wrong direction.
  • Layer-by-layer rotation requires four-way swaps within each concentric square. An off-by-one in the loop bounds causes elements to be swapped with the wrong partners or swapped twice.

Full solution

Transpose across the main diagonal, then reverse each row: two loops anyone can derive on the spot, O(n^2) time with O(1) extra space, and no four-way layer swap whose bounds are easy to get wrong.

Python
from typing import List


def rotate_image(matrix: List[List[int]]) -> None:
    n = len(matrix)
    # transpose: swap only above the diagonal, or every pair is swapped back
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    # reverse each row: transpose alone is a reflection, not a rotation
    for row in matrix:
        row.reverse()
JavaScript
function rotateImage(matrix) {
  const n = matrix.length;
  // transpose: swap only above the diagonal, or every pair is swapped back
  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]];
    }
  }
  // reverse each row: transpose alone is a reflection, not a rotation
  for (const row of matrix) row.reverse();
}
Try it in the editor

The theory behind it

Matrix — the ground this problem stands on. All Matrix problems

What Matrix is

A matrix is a flat grid of cells laid out in rows and columns, like a checkerboard or a spreadsheet. Each cell has an address made of two numbers: its row index going down and its column index going across. Because computer memory stores these rows one after another or as arrays of arrays, jumping straight to any individual cell takes the same tiny fraction of time no matter where it sits on the board.

When to reach for it

Reach for matrix techniques when the input is a two-dimensional grid, board, or map. Common prompts include walking through a maze, finding connected islands of land in water, rotating an image ninety degrees in place, or reading numbers in a spiral. Words like rows, columns, neighbors, adjacent squares, or diagonal lines are clear signs. It also appears in grid planning where each cell depends on the values above and to the left.

How the pattern works

Think of navigating the grid using directional coordinate offsets. Define row and column step arrays for moving up, down, left, and right. Always check that new row and column indices stay strictly between zero and the board boundaries before reading cell values. For spiral scans, track four boundary lines for top, bottom, left, and right, shrinking them inward after reading each side. When searching connected regions, mark visited cells directly or write a marker value into the cell to avoid looping.

What each operation costs

OperationTime
read or write cell by row and columnO(1)
visit every cell across m rows and n columnsO(m * n)
rotate square matrix in placeO(n^2)
What usually goes wrong with Matrix
  • Flipping row and column dimensions by mixing up grid height with grid width, causing index out of bounds crashes on rectangular grids where row and column counts differ.
  • Reading neighbor cells without first confirming that the row and column coordinates are within valid bounds between zero and the board edges.
  • Forgetting to update inner boundary limits during spiral traversal, which causes single-row or single-column matrices to print duplicate entries.

Which roles need this problem

Matrix is a core topic for these 10 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 7 more roles, including Frontend Engineer, Full-Stack Developer, Android Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Matrix problems

Problem set and role mapping as of .