Skip to content
GKgkml.dev
← Problem set
#62MediumDynamic programming

Unique Paths

The tell: Count routes through a grid with restricted moves — a 2-D counting recurrence.

How you get there

  1. 1Each cell is reachable from above or from the left.
  2. 2So paths(r, c) = paths(r-1, c) + paths(r, c-1).
  3. 3Only the previous row matters, so a single row can be rolled forward.

Solution

Python
def unique_paths(m: int, n: int) -> int:
    row = [1] * n
    for _ in range(m - 1):
        for c in range(1, n):
            row[c] += row[c - 1]      # row[c-1] is already this row; row[c] is the row above
    return row[-1]
Time
O(rows · cols)
Space
O(cols)

What goes wrong

Building the table as [[1] * n] * m aliases every row to the same list.