LC 48 — Problem

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise. You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. Do NOT allocate another 2D matrix and do the rotation.

Input: matrix = 123,456,789
Output: 741,852,963
Input: matrix = 51911,24810,13367,15141216
Output: 151325,14341,12689,1671011

Constraints: n == matrix.length == matrix[i].length · 1 ≤ n ≤ 20 · -1000 ≤ matrix[i][j] ≤ 1000

You open a photo editor and hit “rotate 90° clockwise.” Instant. But behind every pixel is an index calculation. In a matrix, rotating means moving every element to a new position — and moving one element displaces whatever was already there.

The rotation formula maps [row][col] to [col][n-1-row] where n is the matrix size. For our 4×4 matrix, element [0][0]=5 goes to [0][3]. But what was at [0][3]? It needs to move too. And whatever IT displaces also needs a new home. This creates a chain — and you are about to trace it.

FIG. 1 — 4 × 4 STARTING MATRIX
— every position participates in a four-way cycle —

Let's trace the displacement chain starting from [0][0]=5. You will tap the grid cell where each displaced element should go. The formula is [r][c] → [c][n-1-r] with n=4.