Skip to content

Unique Paths

MediumLeetCode #62Time O(m * n)Space O(n)

A robot sits at the top-left of an m by n grid and wants the bottom-right corner. It can only step right or down. Return how many different routes exist.

m = 3, n = 7 -> 28
m = 3, n = 2 -> 3 (right-down-down, down-right-down, down-down-right)

Brute force tries every sequence of moves recursively, which is exponential, and it recomputes the same cells over and over. The observation: the last step into a cell must come from directly above or directly to the left, and those are different routes. So the count for a cell is the sum of the two neighbours’ counts.

paths[i][j] = paths[i-1][j] + paths[i][j-1], with the whole first row and first column equal to 1 (only one way to go straight along an edge).

3 x 3 grid, filled left to right, top to bottom:
1 1 1
1 2 3
1 3 6 <- answer is the bottom-right cell

Each row only reads the row above it, so one array is enough. Before you update row[j], it still holds the value from above; row[j-1] was just updated and holds the value from the left. That makes row[j] += row[j - 1] the full recurrence.

There is also a closed form. Every route is m-1 downs and n-1 rights in some order, so the answer is C(m+n-2, m-1). Mention it, but write the DP: it generalizes to obstacles and costs.

Show solutionHide solution
def unique_paths(m: int, n: int) -> int:
row = [1] * n # first row: one way to reach each cell
for _ in range(1, m):
for j in range(1, n):
row[j] += row[j - 1] # row[j] is "from above", row[j-1] is "from left"
return row[-1]
  • Time: O(m * n) — every cell of the grid is visited once, with O(1) work each.
  • Space: O(n) — one row of n counts, reused for every grid row.
  • Initialize the row to 1s, not 0s. The top row has exactly one path per cell; with 0s everything stays 0.
  • Loop j from 1. Column 0 is always 1 and has no left neighbour to add.
  • Don’t compute the binomial with naive factorials. (m+n-2)! overflows fast. Multiply and divide step by step, or just use the DP.

Some cells are blocked. The trick: the same recurrence, but set a blocked cell’s count to 0. Handle the first row and column carefully: everything after a blocker on an edge is also 0.

Each cell has a cost; find the cheapest right/down route. The trick: swap the sum for grid[i][j] + min(above, left). Same table, same single-row reduction.