Skip to main content
mediumBlind 75

Rotate Image

Rotate n x n matrix 90 degrees clockwise in-place Input: 2D square matrix Output: rotated matrix (modify in-place and return)

I rotate the square in place: transpose it, then reverse every row. No second grid needed.

Arrays & HashingMath & Geometry

Examples

You write

rotate(matrix: List[List[int]])

  1. Example 1

    Input
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    returns
    [[7,4,1],[8,5,2],[9,6,3]]
  2. Example 2

    Input
    matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
    returns
    [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Matrix Rotationmedium