AlgoViz

Unique paths

medium 18 min

A robot at the top-left of an m × n grid may only move right or down.

Video lesson · Chapter 1 of 6

Count routes without listing them

0:00 / 5:35

Unique paths in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Set the edges. The top row and left column are all 1s: a straight line is the only way to reach them

Understand it

Start here

A robot, a grid and two moves

A robot stands on the top-left cell of a grid with mm rows and nn columns. It may only move right or down, one cell at a time, and it wants the bottom-right cell. How many different paths can it take? On a 3 × 3 grid the answer is 6; on a 3 × 7 grid it is 28.

  • Start: (0, 0)

    The top-left cell. Rows are numbered 00 to m−1m - 1 from the top, columns 00 to n−1n - 1 from the left.

  • Moves: right or down

    Never up, never left, so the robot can never revisit a cell and every path has the same length.

  • Goal: (m − 1, n − 1)

    The bottom-right cell. Two paths are different if they differ in at least one move.

1D DP2D DP
Stateone index iitwo indices (r,c)(r, c)
Storagean array dp[i]a grid dp[r][c]
Depends ondp[i - 1], dp[i - 2]dp[r - 1][c], dp[r][c - 1]
Examplesclimbing stairs, house robberunique paths, minimum path sum, edit distance, LCS
Think of 2D DP as filling a spreadsheet cell by cell, where each formula only points up and to the left.

The recurrence

Every cell is above plus left

Look at the last move into a cell (r,c)(r, c). It was either a move down from (r−1,c)(r - 1, c) or a move right from (r,c−1)(r, c - 1). Every path is in exactly one of those two groups, so the counts add.

The recurrence

dp[r][c]={1r=0 or c=0dp[r−1][c]+dp[r][c−1]otherwise\text{dp}[r][c] = \begin{cases} 1 & r = 0 \text{ or } c = 0 \\ \text{dp}[r-1][c] + \text{dp}[r][c-1] & \text{otherwise} \end{cases}
Above plus left. The answer is dp[m−1][n−1]\text{dp}[m-1][n-1].

Working out one cell

The two groups never overlap and together cover every path, which is why addition is correct.
  • From above

    The robot was at (r−1,c)(r - 1, c) and moved down. There are dp[r - 1][c] such paths.

  • From the left

    The robot was at (r,c−1)(r, c - 1) and moved right. There are dp[r][c - 1] such paths.

  • No third way

    Up and left moves are not allowed, so no path can enter from below or from the right.

Base cases

The edges are all 1s

To reach a cell on the top row the robot never moved down, so it moved right every time: one path. To reach a cell on the left column it moved down every time: one path. These cells have no cell above or no cell to the left, so they are exactly where the recurrence needs a starting value.

c = 0c = 1c = 2
r = 0111
r = 11??
r = 21??
A 3 × 3 table after the base cases. The four ? cells are filled with the recurrence.

Brute force

Plain recursion and its call tree

Python
def paths(r, c):    """Ways to reach (r, c) from (0, 0) moving right or down."""    if r == 0 or c == 0:        return 1    return paths(r - 1, c) + paths(r, c - 1)def unique_paths(m, n):    return paths(m - 1, n - 1)print(unique_paths(3, 3), unique_paths(3, 7))   # 6 28
The recurrence written as recursion. Correct, and a good first draft, but slow.
Edit and run it in your browser

Call tree of f(2, 2) on a 3 × 3 grid

11 calls for 8 different cells. The red subtree is work that was already done on the left.

Leaves are paths

#leaves=paths,#calls=2⋅paths−1=2(m+n−2m−1)−1\#\text{leaves} = \text{paths}, \qquad \#\text{calls} = 2 \cdot \text{paths} - 1 = 2\binom{m+n-2}{m-1} - 1
Every leaf returns 1 and inner calls only add, so the answer is the number of leaves. A tree where every inner node has two children and LL leaves has 2L−12L - 1 nodes: 2⋅6−1=112 \cdot 6 - 1 = 11 for 3 × 3.

Complexity

Why brute force explodes

A quick upper bound

depth≤(m−1)+(n−1),branching=2⟹T(m,n)=O(2m+n)\text{depth} \le (m-1) + (n-1), \quad \text{branching} = 2 \quad\Longrightarrow\quad T(m, n) = O\big(2^{m+n}\big)
Each call lowers r+cr + c by one, so no root-to-leaf path is longer than m+n−2m + n - 2 calls. The stack holds one such path: O(m+n)O(m + n) space.

The tight rate for a square grid

(2n−2n−1)≈4 n−1π(n−1)\binom{2n-2}{n-1} \approx \frac{4^{\,n-1}}{\sqrt{\pi (n-1)}}
From Stirling's formula. For an n×nn \times n grid the work grows about 4 times with each extra row and column, even though there are only n2n^2 different cells.
GridPathsBrute-force callsMemoised callsDistinct cells
3 × 361199
3 × 728552521
10 × 1048,62097,239163100
16 × 16155,117,520310,235,039451256
Brute force makes 2⋅paths−12 \cdot \text{paths} - 1 calls; memoisation makes 1+2(m−1)(n−1)1 + 2(m - 1)(n - 1).

Fix 1

Memoisation: each cell once

A memoised call

Each inner cell reaches the bottom box at most once, so there are at most (m−1)(n−1)(m-1)(n-1) real computations.
Python
from functools import cachedef unique_paths_memo(m, n):    memo = {}    def paths(r, c):        if r == 0 or c == 0:            return 1        if (r, c) in memo:            return memo[(r, c)]        memo[(r, c)] = paths(r - 1, c) + paths(r, c - 1)        return memo[(r, c)]    return paths(m - 1, n - 1)def unique_paths_cached(m, n):    @cache    def paths(r, c):        return 1 if r == 0 or c == 0 else paths(r - 1, c) + paths(r, c - 1)    return paths(m - 1, n - 1)print(unique_paths_memo(10, 10), unique_paths_cached(23, 12))   # 48620 193536720
With a dictionary, and the same thing with functools.cache.
Edit and run it in your browser

Fix 2

Bottom-up: fill the table

The bottom-up recipe
  1. 1Create gridan m × n table
  2. 2Init edgesrow 0 and column 0 = 1
  3. 3Fill tabletop + left, row by row
  4. 4Resultdp[m - 1][n - 1]
Python
def unique_paths(m, n):    dp = [[0] * n for _ in range(m)]   # one separate list per row    for c in range(n):        dp[0][c] = 1                   # top row    for r in range(m):        dp[r][0] = 1                   # left column    for r in range(1, m):        for c in range(1, n):            dp[r][c] = dp[r - 1][c] + dp[r][c - 1]    return dp[m - 1][n - 1]for row in [[unique_paths(r, c) for c in range(1, 6)] for r in range(1, 6)]:    print(row)
The standard solution: O(m⋅n)O(m \cdot n) time, O(m⋅n)O(m \cdot n) space, no recursion.
Edit and run it in your browser
c = 0c = 1c = 2
r = 0111
r = 112 = 1 + 13 = 1 + 2
r = 213 = 2 + 16 = 3 + 3
The 3 × 3 table, filled in the order (1, 1), (1, 2), (2, 1), (2, 2). Each cell's above and left are always ready.

Space

One row is enough

Row rr only reads row r−1r - 1 and itself. So keep one array row of length nn. Just before row[c] is updated it still holds the old value, the cell above; row[c - 1] was already updated, the cell to the left. One line does the whole job: row[c] += row[c - 1].

Turning row 1 into row 2 in place (3 × 7)

Left of the pointer is the new row, from the pointer on is the old row. The last cell, 28, is the answer.
Python
def unique_paths(m, n):    if n > m:        m, n = n, m                  # paths(m, n) == paths(n, m): keep the row short    row = [1] * n                    # the top row    for _ in range(1, m):        for c in range(1, n):            row[c] += row[c - 1]     # above (old) + left (new)    return row[n - 1]print(unique_paths(3, 7), unique_paths(7, 3), unique_paths(10, 10))   # 28 28 48620
O(m⋅n)O(m \cdot n) time, O(n)O(n) space. Swap so the row runs along the shorter side for O(min⁡(m,n))O(\min(m, n)).
Edit and run it in your browser

The math

Count the moves: C(m + n − 2, m − 1)

Every path makes exactly m−1m - 1 downs and n−1n - 1 rights, m+n−2m + n - 2 moves in all; only the order differs. Writing a path as a string like DRDR, a path is fixed once you choose which positions hold the Ds. So the number of paths is a binomial coefficient.

The closed form

paths(m,n)=(m+n−2m−1)=(m+n−2n−1)=(m+n−2)!(m−1)! (n−1)!\text{paths}(m, n) = \binom{m+n-2}{m-1} = \binom{m+n-2}{n-1} = \frac{(m+n-2)!}{(m-1)!\,(n-1)!}
Choosing the downs is the same as choosing the rights, which is why the answer is symmetric in mm and nn. See combinations and permutations.

Worked examples

3×3:(42)=4⋅32⋅1=63×7:(82)=8⋅72=2810×10:(189)=48,6203 \times 3: \binom{4}{2} = \frac{4 \cdot 3}{2 \cdot 1} = 6 \qquad 3 \times 7: \binom{8}{2} = \frac{8 \cdot 7}{2} = 28 \qquad 10 \times 10: \binom{18}{9} = 48{,}620
Compute it by multiplying and dividing one factor at a time, k=min⁡(m,n)−1k = \min(m, n) - 1 steps: O(min⁡(m,n))O(\min(m, n)) time, O(1)O(1) space. In Python, math.comb does it exactly.

The table is Pascal's triangle

dp[r][c]=(r+cr),(kj)=(k−1j−1)+(k−1j)\text{dp}[r][c] = \binom{r+c}{r}, \qquad \binom{k}{j} = \binom{k-1}{j-1} + \binom{k-1}{j}
The DP rule (above plus left) is Pascal's rule turned 45 degrees. Read any anti-diagonal of the table, r+c=kr + c = k, and you get row kk of Pascal's triangle, such as 1, 4, 6, 4, 1.

Variant

Unique Paths II: rocks on the grid

One cell, with obstacles

A rock is just a cell forced to 0. Missing neighbours on the edges count as 0, so the edges are handled by the same rule.
c = 0c = 1c = 2c = 3
r = 011# 00
r = 11222
r = 21# 024
r = 31137
A 4 × 4 grid with rocks at (0, 2) and (2, 1). Without rocks there are (63)=20\binom{6}{3} = 20 paths; with them, 7. Note (0,3)=0(0, 3) = 0: past a rock on the top row nothing is reachable.
Python
def unique_paths_with_obstacles(grid):    n = len(grid[0])    row = [0] * n    row[0] = 1                         # one way to stand at the start (if it is open)    for cells in grid:        for c in range(n):            if cells[c] == 1:                row[c] = 0             # rock: nothing reaches or passes through it            elif c > 0:                row[c] += row[c - 1]   # above (old) + left (new)    return row[n - 1]print(unique_paths_with_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]]))   # 2print(unique_paths_with_obstacles([[0, 0, 1, 0], [0, 0, 0, 0],                                   [0, 1, 0, 0], [0, 0, 0, 0]]))        # 7print(unique_paths_with_obstacles([[1]]))                                # 0
Unique Paths II. grid[r][c] == 1 marks a rock. One rolling row is enough here too.
Edit and run it in your browser

Choosing

Which approach, and the grid DP family

ApproachTimeSpaceEasy to explainHandles rocks
Plain recursionO(2m+n)O(2^{m+n})O(m+n)O(m + n) stackYesYes, but too slow
Memoised recursionO(m⋅n)O(m \cdot n)O(m⋅n)O(m \cdot n)YesEasy
2D tableO(m⋅n)O(m \cdot n)O(m⋅n)O(m \cdot n)YesEasy
One rolling rowO(m⋅n)O(m \cdot n)O(min⁡(m,n))O(\min(m, n))MostlyEasy
Binomial formulaO(min⁡(m,n))O(\min(m, n))O(1)O(1)Needs the counting ideaNo
In an interview, write the 2D table first, then offer the one-row version and mention the formula.

Which version to write

The table is the version that survives every twist, which is why interviewers want to see it.
  • Minimum path sum

    Each cell has a cost. Replace the sum by a minimum: dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1]).

  • Four directions

    If the robot may also go up or left, paths can loop and the table has no fill order. Use BFS or DFS with a visited set instead; see matrix BFS.

  • Track the actual path

    Store which neighbour each cell came from (or walk back through the table choosing a neighbour with a nonzero count) to rebuild a path.

  • Two strings as a grid

    Edit distance and longest common subsequence fill a table indexed by two string positions with the same above, left and diagonal pattern.

One rolling row

  • O(min⁡(m,n))O(\min(m, n)) memory: 7 cells instead of 21 for 3 × 7.
  • Same O(m⋅n)O(m \cdot n) time and the same answers.
  • Works with rocks too.

Full 2D table

  • O(m⋅n)O(m \cdot n) memory.
  • But easier to read, debug and print.
  • Needed if you must rebuild the path afterwards.

Recap

Key takeaways

Key points

  • dp[r][c] = number of ways to reach (r, c); the answer is dp[m - 1][n - 1].
  • The last move came from above or from the left, so dp[r][c] = dp[r - 1][c] + dp[r][c - 1].
  • Top row and left column are 1; the start counts as 1, so a 1 × 1 grid has 1 path.
  • Plain recursion makes 2 × paths − 1 calls: exponential. Memoisation or a table gives O(m·n).
  • One rolling row, updated left to right with row[c] += row[c - 1], needs only O(min(m, n)) space.
  • Closed form: C(m + n − 2, m − 1), choosing which moves are downs. 3 × 3 = 6, 3 × 7 = 28.
  • Rocks are cells forced to 0; never pre-fill the edges with 1s when rocks are possible.

Sources