Practice

Rotate Image

Module 15 · Matrix / 2D Traversal

Problem

You are given an n × n 2D matrix representing an image. Rotate the image by 90 degrees clockwise, in place — you must modify the input matrix directly and may not allocate another 2D matrix to do it. (LeetCode 48.)

Examples

Example 1

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

Example 2

Inputmatrix = [[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, values in ±1000. The in-place / no-extra-matrix requirement is part of the problem, not a bonus.

Attempt it first

This problem is a direct application of the previous concept lesson (In- Place Transformations) — that's deliberate. Before revealing anything, try to answer the two questions the concept lesson set up: what is the target position (r, c) rotates to under a 90° clockwise turn, and which two in-place reflections compose to produce that map? If you can write down where (r, c) lands, the code writes itself. Try it, then open the hint only if you're stuck on the decomposition.