In-place Matrix Manipulation
Decompose the transform into reversible operations such as transpose plus row reversal, or walk boundaries layer by layer.
MatrixO(rows * cols)New12 problems
18
mastery
Trigger phrases
If a problem statement sounds like one of these, try this pattern first.
rotate image
spiral order
set matrix zeroes
transpose
The template
Get this into muscle memory, then adapt the condition per problem.
// rotate 90 clockwise, in place
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
[m[i][j], m[j][i]] = [m[j][i], m[i][j]];
for (const row of m) row.reverse();If you are stuck
The generic hint ladder for this pattern, in order.
- 1Extra space is banned, so find a composition of in-place steps.
- 2Transpose then reverse each row rotates clockwise.
- 3For spiral order, maintain four moving boundaries.
Drill it
Every problem in the bank that uses this pattern.
0 / 12 solved