Math & Geometry
Peel an orange in one long strip: go around the outside, then around what’s left, and never touch the same skin twice. A grid works the same way. Four walls mark what’s left, and each side you walk pulls one wall in.
2 · Watch
Math & Geometry in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Spiral Matrix
or try
1–5 rows of 1–5 numbers from 0 to 99. Put | between rows.A 3 by 4 grid. Four walls start around the whole thing.Step 1 of 22. 3 rows and 4 columns.
Step 1 of 22
solution.ts
function spiralOrder(grid: number[][]): number[] {
const out: number[] = [];
let top = 0, bottom = grid.length - 1;
let left = 0, right = grid[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) out.push(grid[top][c]);
top++;
for (let r = top; r <= bottom; r++) out.push(grid[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(grid[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(grid[r][left]);
left++;
}
}
return out;
}
▶ marks the line running now
4 · Your turn
0 of 3 problems solved
Start from this
// Four walls mark what's left to read.
let top = 0, bottom = grid.length - 1;
let left = 0, right = grid[0].length - 1;
while (top <= bottom && left <= right) {
// Walk one side, then pull that wall in.
for (let c = left; c <= right; c++) out.push(grid[top][c]);
top++;
for (let r = top; r <= bottom; r++) out.push(grid[r][right]);
right--;
// Recheck: a single row or column has no way back.
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(grid[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(grid[r][left]);
left++;
}
}
// Rotate 90° clockwise: flip across the diagonal, then mirror each row.
for (let r = 0; r < n; r++) {
for (let c = r + 1; c < n; c++) {
[grid[r][c], grid[c][r]] = [grid[c][r], grid[r][c]];
}
}
for (const row of grid) row.reverse();Easy ways to go wrong
- Dropping the recheck, so a single row or column gets read twice.
- Mixing up rows and columns on a grid that isn't square.
- Overwriting a cell you still need. Change the order, or save it first.
- Medium01
Spiral Matrix
The one you just watched. Write it from memory.
Track four walls and pull each one in after you walk it.
- Time
- O(m·n)
- Space
- O(1)
- Medium02
Rotate Image
Flip across the diagonal, then mirror each row.
Flip across the diagonal, then reverse each row.
- Time
- O(n²)
- Space
- O(1)
- Medium03
Set Matrix Zeroes
Use the first row and column as notes.
Use the first row and column as your notepad.
- Time
- O(m·n)
- Space
- O(1)