Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 10 minutesNeeds: 2D arraysTime O(m·n)Space O(1)

2 · Watch

Math & Geometry in 60 seconds

Read this grid in a spiral, from the outside in. One way is a second grid that marks every cell you’ve seen. That’s 12 extra numbers.

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.
  1. Medium01

    Spiral Matrix

    LeetCode 54 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  2. Medium02

    Rotate Image

    LeetCode 48 · Blind 75 · NeetCode 150

    Flip across the diagonal, then mirror each row.

  3. Medium03

    Set Matrix Zeroes

    LeetCode 73 · Blind 75 · NeetCode 150

    Use the first row and column as notes.

UP NEXT · LESSON 20 OF 20Bit ManipulationUse AND, XOR and shifts to work on single bits.