Blind 75 · Math & Geometry

Rotate Image

Medium

Problem

Given an n x n matrix, return it rotated 90 degrees clockwise: the first row becomes the last column, the last row becomes the first column.
The classic version demands the rotation in place; here you return the rotated grid, and the in-place transpose-then-reverse trick is still the technique worth knowing.

Examples

Example 1:
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 = [[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]]

Example 3:
Input: matrix = [[1]]
Output: [[1]]

Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints

1 <= n <= 20
-1000 <= matrix[i][j] <= 1000

Prerequisites

Index arithmetic on a grid, and the discipline of writing the coordinate rule down before coding it.

How to think about it

1. One Coordinate Rule Optimal

Intuition

Write the rule down before writing code: a clockwise quarter turn sends the value at (row, column) to (column, n-1-row). With a fresh grid that is a two-line loop. The in-place version composes two reflections — transpose across the diagonal, then reverse each row — and being able to explain WHY that equals a rotation is what the question is really testing.

Algorithm

1. Allocate an n x n result.
2. For every (r, c), place the original value at (c, n-1-r).

Time & Space

Time O(n^2). Space O(n^2) here; O(1) for the transpose-then-reverse version.