Unique paths
medium 18 minA robot at the top-left of an m × n grid may only move right or down.
See it run
Watch a robot's path count grow from the edges inwards, one cell at a time, as each cell adds the cell above it and the cell to its left.
Operations
2D table: 3 × 3 grid
Fill dp[r][c], the number of ways to reach cell (r, c), for a 3 × 3 grid. The top row and left column are all 1s; every other cell is the cell above plus the cell to the left. The answer lands in the bottom-right corner.
Step 1 of 8
An empty 3 × 3 table
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | · | · | · |
| 1 | · | · | · |
| 2 | · | · | · |
start (0, 0) → goal (2, 2), moves: right or down
The robot starts at the top-left cell (0, 0) and wants the bottom-right cell (2, 2). It may only move right or down. We make a table the same shape as the grid, where dp[r][c] will hold the number of different ways to reach cell (r, c).
Step 1: An empty 3 × 3 table
def unique_paths(m, n): dp = [[0] * n for _ in range(m)] for c in range(n): dp[0][c] = 1 # top row: only moves right for r in range(m): dp[r][0] = 1 # left column: only moves down for r in range(1, m): for c in range(1, n): dp[r][c] = dp[r - 1][c] + dp[r][c - 1] # from above + from the left return dp[m - 1][n - 1]- Time
- O(m·n)
- Space
- O(m·n)
- cells computed
- (m − 1)(n − 1) = 4
- brute force
- 11 calls here
- answer
- 6 paths
Say the recurrence out loud before you code: the last move came from above or from the left, so dp[r][c] = dp[r - 1][c] + dp[r][c - 1].
In the real world
The same unique paths doing real jobs. Pick one and step through it.
The smallest grid with a real choice. Two moves, one down and one right, in either order: two paths.
Step 1 of 4
Start and goal
| 0 | 1 | |
|---|---|---|
| 0 | · | · |
| 1 | · | · |
start (0, 0) → goal (1, 1)
The robot is at (0, 0) and the goal is (1, 1): one row down and one column right.
Step 1: Start and goal
print(unique_paths(2, 2)) # 2: "RD" and "DR"Common mistakes
The bugs interviewers watch for, with the fix beside each.
Building the table with [[0] * n] * m
criticalMultiplying a list of lists copies the reference, not the row. All m rows are the same list, so writing dp[1][1] also writes dp[0][1], dp[2][1] and every other row. Build each row separately.
Wrongdp = [[0] * n] * m # m references to ONE rowdp[1][1] = 2print(dp[0][1]) # 2: the "top row" changed tooRightdp = [[0] * n for _ in range(m)] # m separate rowsdp[1][1] = 2print(dp[0][1]) # 0Looping from 0 and reading dp[-1]
criticalPython's negative indices do not raise an error: dp[r - 1][c] with r = 0 quietly reads the last row. The answer comes out wrong with no crash. Start the loops at 1 after setting the edges, or guard r > 0 and c > 0.
Wrongfor r in range(m): for c in range(n): dp[r][c] = dp[r - 1][c] + dp[r][c - 1] # r = 0 reads dp[-1]: the bottom rowRightfor r in range(1, m): for c in range(1, n): dp[r][c] = dp[r - 1][c] + dp[r][c - 1] # edges were set to 1 firstFilling the edges with 1s when there are rocks
criticalWith obstacles, a rock on the top row blocks every cell to its right, and a rock on the left column blocks every cell below it. Pre-filling the edges with 1s counts paths that walk straight through the rock.
Wrongfor c in range(n): dp[0][c] = 1 # (0, 3) gets 1 even with a rock at (0, 2)Rightfor c in range(n): if grid[0][c] == 1: break # everything past the rock stays 0 dp[0][c] = 1Updating the rolling row right to left
majorIn the one-row version, row[c - 1] must already be the new row (the left cell) while row[c] is still the old row (the cell above). Going right to left reads the old row[c - 1], which is the cell above-left, so you add the wrong cells: a 3 × 3 grid gives 4 instead of 6.
Wrongfor _ in range(1, m): for c in range(n - 1, 0, -1): # right to left row[c] += row[c - 1] # row[c - 1] is still the old rowRightfor _ in range(1, m): for c in range(1, n): # left to right row[c] += row[c - 1] # row[c - 1] already updated: the left cellComputing the binomial with float division
majorfactorial(a) / (factorial(b) * factorial(c)) uses true division and returns a float. Floats hold about 16 significant digits, so large answers come back rounded, and the result is 6.0 rather than 6 even when it is right.
Wrongfrom math import factorialdef unique_paths(m, n): return factorial(m + n - 2) / (factorial(m - 1) * factorial(n - 1)) # floatRightfrom math import combdef unique_paths(m, n): return comb(m + n - 2, m - 1) # exact integerSubmitting the plain recursion
minorThe brute force makes 2 × paths − 1 calls: about 97,000 for 10 × 10 and hundreds of millions by 16 × 16. It is a fine first draft to show the recurrence, but cache it or fill a table before you finish.
Wrongdef paths(r, c): if r == 0 or c == 0: return 1 return paths(r - 1, c) + paths(r, c - 1) # exponentialRightfrom functools import cache@cachedef paths(r, c): if r == 0 or c == 0: return 1 return paths(r - 1, c) + paths(r, c - 1) # each cell once: O(m·n)
Interview tips
How to explain it
- The last move into a cell came from above or from the left, and those groups never overlap, so dp[r][c] = dp[r - 1][c] + dp[r][c - 1].
- The top row and left column are 1: a straight line is the only way there.
- Fill row by row: O(m·n) time; keep one row for O(n) space; or answer C(m + n − 2, m − 1) directly.
Spot it in problems
- A grid, moves restricted to right and down (or any two directions that never go back).
- "How many ways" or "minimum cost" to get from one corner to the other.
- Blocked cells, costs per cell, or a target cell: the same table with a different rule per cell.
Memory tricks
- GRID: Grid of subproblems, Right and down only, Initialise the edges to 1, Derive each cell from top + left.
- Above plus left, edges are one.
- 3 × 3 is 6, 3 × 7 is 28, 10 × 10 is 48,620.
Watch out
- [[0] * n] * m shares one row between all rows.
- Negative indices wrap silently in Python: never read dp[-1].
- With rocks, the edges are not all 1s.
- m is rows and n is columns: dp[m - 1][n - 1] is the answer, dp[m][n] is out of range.