Unique Paths II solution explained
Unique Paths II asks how many routes lead from the top-left to the bottom-right cell of a grid when you may only move right or down and some cells are blocked. The number of ways to reach a free cell is the ways to reach the cell above plus the ways to reach the cell to its left, and a blocked cell has zero ways. Filling the grid in reading order with that rule gives the answer in O(rows × cols) time and only one row of memory.
By Evin JohnPublished 7 min read
The problem, in plain terms
You get a rectangular grid where each cell is either open (0) or blocked (1). A robot starts in the top-left cell and wants to reach the bottom-right cell. On each move it steps one cell right or one cell down, never left or up, and it cannot enter a blocked cell. Count the distinct routes. If the start or the finish is blocked, the count is 0.
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 0 | 0 | 0 | 0 |
| row 1 | 0 | 1 | 0 | 0 |
| row 2 | 0 | 0 | 0 | 1 |
| row 3 | 1 | 0 | 0 | 0 |
This grid has 3 routes. Without obstacles a 4 by 4 grid has 20, so three blocked cells remove most of them, which already hints that you cannot reason about obstacles one at a time; you need a method that counts what actually gets through.
Why interviewers like it
It is often the problem that introduces dynamic programming in a loop of interviews. The recurrence is short, the obstacle twist rules out a combinatorics formula, and it tests whether you can move from a recursive idea to a table and then to a single row. Interviewers also listen for how you handle the first row and column, where most mistakes happen.
Brute force, then memoized recursion
from functools import lru_cache
def count_paths_brute(grid):
"""Try every route. Exponential: only for tiny grids and for testing."""
rows, cols = len(grid), len(grid[0])
def walk(r, c):
if r >= rows or c >= cols or grid[r][c] == 1:
return 0
if r == rows - 1 and c == cols - 1:
return 1
return walk(r + 1, c) + walk(r, c + 1)
return walk(0, 0)
def count_paths_memo(grid):
"""Same recursion, each cell solved once: O(rows * cols)."""
rows, cols = len(grid), len(grid[0])
@lru_cache(maxsize=None)
def ways(r, c):
if r >= rows or c >= cols or grid[r][c] == 1:
return 0
if r == rows - 1 and c == cols - 1:
return 1
return ways(r + 1, c) + ways(r, c + 1)
return ways(0, 0)The brute force recomputes the same cells again and again: many routes pass through the middle of the grid, and each one re-walks everything after it. Caching ways(r, c) means each cell is solved once. That memoized version is a perfectly good interview answer. Two caveats: Python's default recursion limit can be hit on very tall or wide grids (it recurses about rows + cols deep), and interviewers often ask for the iterative version next.
Bottom-up with one row
Think of row[c] as "the number of ways to reach column c in the current row". Before you update it, it still holds the value for the row above. Adding row[c - 1], which was just updated for the current row, adds the ways coming from the left. A blocked cell resets the slot to zero. The start cell is seeded with 1 if it is open.
def count_paths(grid):
"""Bottom-up with one row of memory: O(rows * cols) time, O(cols) space."""
cols = len(grid[0])
row = [0] * cols
row[0] = 1 if grid[0][0] == 0 else 0
for r in range(len(grid)):
for c in range(cols):
if grid[r][c] == 1:
row[c] = 0 # nobody gets through a blocked cell
elif c > 0:
row[c] += row[c - 1] # from above (old value) + from the left
return row[-1]function countPaths(grid) {
const cols = grid[0].length;
const row = new Array(cols).fill(0);
row[0] = grid[0][0] === 0 ? 1 : 0;
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 1) row[c] = 0;
else if (c > 0) row[c] += row[c - 1];
}
}
return row[cols - 1];
}Python integers never overflow. JavaScript numbers are exact only up to 2^53, and route counts grow fast: an empty 30 by 30 grid already has more routes than that. If your inputs can be that large, store BigInt values (1n, 0n) in the row; the logic does not change.
A trace on the example grid
| After row | col 0 | col 1 | col 2 | col 3 | What happened |
|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | Only one way along the open top edge |
| 1 | 1 | 0 | 1 | 2 | Block at col 1 zeroes it; col 3 gets 1 from above + 1 from left |
| 2 | 1 | 1 | 2 | 0 | Block at col 3 zeroes it |
| 3 | 0 | 1 | 3 | 3 | Block at col 0; the finish collects 3 from the left, 0 from above |
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Walk every route | Exponential in R + C | O(R + C) recursion |
| Memoized recursion | O(R × C) | O(R × C) cache + O(R + C) stack |
| Full 2D table | O(R × C) | O(R × C) |
| One row (above) | O(R × C) | O(C) |
If the grid is much taller than wide, keep the row array along the shorter side by iterating column by column instead. And if you are allowed to change the input, you can store the counts in the grid itself for O(1) extra memory, though many interviewers prefer you not mutate the input without asking.
Edge cases
- Start blocked: 0. The seed line handles it.
- Finish blocked: 0. The loop zeroes the last slot.
- A single cell that is open: 1 route (you are already there).
- One row or one column: 1 if every cell is open, otherwise 0, because a single block cuts the only route.
- Large open grids: route counts exceed 32-bit integers quickly; use 64-bit or big integers where the language needs it.
Where answers go wrong
- Initializing the whole first row and first column to 1, ignoring that cells after a block on the edge are unreachable.
- Seeding the start with 1 even when it is blocked.
- Updating the row from right to left, which mixes old and new values the wrong way.
- Using the obstacle-free formula (a binomial coefficient) and trying to subtract routes through blocks; overlaps make that messy and error-prone.
- Forgetting to say what the table means. "row[c] is the number of ways to reach column c in the current row" is the sentence that makes the code reviewable.
How to explain it out loud
Fictional example
- Candidate
- Every route into a cell arrives from above or from the left, so the count for a cell is the sum of those two counts, or zero if the cell is blocked. That gives me a recursion from the finish backward.
- Candidate
- The recursion repeats work, so I will fill a table in reading order instead. Each cell only needs the cell above and the cell to its left, so I can keep one row and overwrite it as I go.
- Interviewer
- What does the array hold halfway through a row?
- Candidate
- To the left of the current column it holds counts for this row; from the current column rightward it still holds the previous row. That is exactly what the update needs.
Same idea, other problems
- Cheapest route through a grid of costs. Replace the sum with a minimum plus the cell's cost.
- Routes when diagonal moves are also allowed. Add the up-left neighbor to the sum.
- Routes that must pass through a given cell. Multiply the routes from start to that cell by the routes from that cell to the finish.
Related walkthroughs
Triangle uses the same one-row trick on a different shape and asks for a minimum instead of a count. Maximal Square is another grid DP where each cell looks at its top, left and top-left neighbors. For a grid problem solved by search rather than counting, see Number of Islands. The full list is on the coding problems hub.
Rehearsing DP explanations with Natively
DP answers are judged on the definition of the table as much as on the code. When you rehearse with a friend or alone, Natively can transcribe the session on your Mac or Windows computer, and the transcript shows whether you defined row[c] before writing it. You can also screenshot a practice grid problem and ask for a hint on the recurrence without seeing a full solution. The coding interview assistant page covers how that works.
Questions people ask
How do you solve Unique Paths II?
Fill the grid in reading order: the number of ways to reach an open cell is the ways to reach the cell above plus the cell to its left, and a blocked cell has zero ways. The bottom-right value is the answer.
What is the time complexity of Unique Paths II?
O(rows × cols) time. With one array the width of the grid, extra memory is O(cols).
What if the start or end cell is blocked?
Then there are no routes and the answer is 0. Seed the start with 1 only when it is open.
Why is Unique Paths II dynamic programming?
Every route into a cell comes from above or from the left, so the count for a cell is built from two smaller, already-solved counts, and each cell is solved once.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
