◀ THE GRIND — 2-D DYNAMIC PROGRAMMING

Unique Paths

MEDIUM✓ CHIP-TIMEDLC #62 — FULL STATEMENT ↗

The drill: A runner starts in the top-left corner of an m×n grid and can only step right or down. Count how many distinct routes reach the bottom-right corner.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A runner starts in the top-left corner of a grid with m rows and n columns, and every move can only go one step right or one step down. The task is to count how many distinct routes reach the bottom-right corner.

Two routes are different if they take their right/down steps in a different order anywhere along the way, even if they pass through the exact same set of cells overall. There are no obstacles to dodge in this version — every cell can be stepped on.

The output required is simply that total count of distinct routes.

EX 01
m = 1 · n = 1
1
SINGLE CELL, ALREADY THERE
EX 02
m = 1 · n = 6
1
SINGLE ROW, ONLY RIGHT MOVES POSSIBLE
EX 03
m = 6 · n = 1
1
SINGLE COLUMN, ONLY DOWN MOVES POSSIBLE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every route is a sequence of right and down steps — a cell reached partway through looks identical no matter which order the earlier steps came in. What does that overlap suggest?

HINT 2 THE STRUCTURE

The number of ways to reach a cell is just the ways to reach the cell above it plus the ways to reach the cell to its left — every route arrives from exactly one of those two neighbours.

HINT 3 ONE STEP FROM THE ANSWER

Fill a table with ways[r][c] = ways[r-1][c] + ways[r][c-1], seeded with 1s along the first row and column. Only the previous row of the table is ever needed again.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE TABLE FILLPATTERN · 2-D DPa 3×3 grid, moves: right or down
1
STEP 1

One way to stand at the start: doing nothing. That seeds the whole table.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/unique-paths.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        row = [1] * n
        for _ in range(m - 1):
            for c in range(1, n):
                row[c] += row[c - 1]
        return row[-1]
TIME O(M·N)SPACE O(N)PYTHON · RACE PACE · 7 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED