Unique Paths solution explained
Unique Paths counts the routes from the top-left to the bottom-right corner of a grid when you may only step right or down. Each cell's count is the count of the cell above plus the cell to its left, which fills the grid in O(rows · cols) time and needs only one row of memory. Because every route is just an ordering of the same right and down moves, the count is also the binomial coefficient C(rows + cols - 2, rows - 1).
By Evin JohnPublished 7 min read
The problem, restated
A delivery robot starts at the top-left square of a warehouse floor laid out as a grid of r rows and c columns. It can only roll one square right or one square down at a time, and it must finish at the bottom-right square. Count the distinct routes. Two routes differ if they ever visit a different square.
| Rows x columns | Routes | Reason |
|---|---|---|
| 1 x 5 | 1 | Only right moves, so a single route |
| 2 x 2 | 2 | Right then down, or down then right |
| 3 x 3 | 6 | Choose which 2 of the 4 moves are downs |
| 3 x 4 | 10 | Choose which 2 of the 5 moves are downs |
| 4 x 4 | 20 | Choose which 3 of the 6 moves are downs |
Why it gets asked
This is often the first grid-shaped dynamic programming problem a candidate sees, and it sets up the table-filling habit used by harder grid problems such as edit distance. It also has a clean math answer, so the interviewer can see whether you notice the structure behind the recurrence. Both answers are fine; knowing both and explaining when each is safer is better.
Follow-ups
- Some cells are blocked. A blocked cell has zero routes through it. The formula no longer applies, but the table does with one extra check.
- Each cell has a cost; find the cheapest route. Replace the sum with a minimum: cost(i, j) = cell cost + min(above, left).
- Very large grids. The count grows fast. Python integers are exact at any size; in JavaScript or C++ say where 64-bit or double precision runs out.
- Three moves allowed, including diagonal. Add the upper-left neighbor to the sum.
Brute force
Walk every route recursively: from the current cell, try going right and try going down, and count the routes that reach the corner. The call tree branches twice at almost every level, so it is exponential in r + c. Even a 15 by 15 grid has tens of millions of routes. The redundancy is obvious once you draw it: many different routes pass through the same cell, and the number of ways to finish from that cell is recomputed every time.
Dynamic programming on the grid
Turn it around and count how many ways reach each cell. A cell can only be entered from directly above or directly to the left, so its count is the sum of those two counts. The top row and left column are all 1s, since along an edge there is only one way to get there. Fill the grid row by row and read the answer from the last cell.
| Col 1 | Col 2 | Col 3 | Col 4 | |
|---|---|---|---|---|
| Row 1 | 1 | 1 | 1 | 1 |
| Row 2 | 1 | 2 | 3 | 4 |
| Row 3 | 1 | 3 | 6 | 10 |
def unique_paths_grid(rows, cols):
ways = [[1] * cols for _ in range(rows)]
for i in range(1, rows):
for j in range(1, cols):
ways[i][j] = ways[i - 1][j] + ways[i][j - 1]
return ways[rows - 1][cols - 1]Each row only looks at the row above it, so a single list can be updated in place. Before the update, row[j] still holds the value from the previous row (the cell above); row[j - 1] has already been updated (the cell to the left). Adding them gives the new value.
def unique_paths(rows, cols):
row = [1] * cols
for _ in range(1, rows):
for j in range(1, cols):
row[j] += row[j - 1] # above + left
return row[-1]function uniquePaths(rows, cols) {
const row = new Array(cols).fill(1);
for (let i = 1; i < rows; i++) {
for (let j = 1; j < cols; j++) {
row[j] += row[j - 1];
}
}
return row[cols - 1];
}The counting shortcut
Every route uses exactly r - 1 down moves and c - 1 right moves, r + c - 2 moves in total. A route is fully described by which of those positions are downs. So the number of routes is the number of ways to choose r - 1 positions out of r + c - 2, the binomial coefficient. In Python, math.comb computes it exactly (it was added in Python 3.8). In JavaScript, BigInt keeps the arithmetic exact, and multiplying then dividing one factor at a time keeps every intermediate value a whole number.
from math import comb
def unique_paths_formula(rows, cols):
return comb(rows + cols - 2, rows - 1)function uniquePathsBig(rows, cols) {
const n = BigInt(rows + cols - 2);
const k = BigInt(Math.min(rows, cols) - 1);
let result = 1n;
for (let i = 1n; i <= k; i++) {
result = (result * (n - k + i)) / i; // whole number after every step
}
return result;
}With blocked cells
The most common follow-up marks some cells as walls. A wall has zero routes into it, and the same above-plus-left rule handles everything else. Note that a wall on the first row also blocks every cell to its right on that row, which the rolling version gets for free, while a version that pre-fills the edges with 1s gets wrong.
def unique_paths_blocked(grid):
cols = len(grid[0])
row = [0] * cols
row[0] = 1
for i in range(len(grid)):
for j in range(cols):
if grid[i][j] == 1:
row[j] = 0
elif j > 0:
row[j] += row[j - 1]
return row[-1]Complexity
| Approach | Time | Extra memory | Handles walls? |
|---|---|---|---|
| Recursive enumeration | Exponential in r + c | O(r + c) stack | Yes |
| Full table | O(r · c) | O(r · c) | Yes |
| Rolling row | O(r · c) | O(c) | Yes |
| Binomial coefficient | O(min(r, c)) multiplications | O(1) numbers | No |
Edge cases
- A 1 x 1 grid: the robot already stands on the goal, which counts as one route.
- A single row or a single column: exactly one route.
- A wall on the start or the goal cell: zero routes.
- Large square grids. For square grids the count first passes 2^53, the exact-integer limit of JavaScript numbers, at 30 x 30, and passes 64-bit integers at 35 x 35.
Common mistakes
- Mixing up rows and columns in the formula. C(r + c - 2, r - 1) and C(r + c - 2, c - 1) are equal, so either choice is correct, but the total must be r + c - 2.
- Pre-filling the first row with 1s in the walled version, which ignores walls along the edge.
- Computing factorials separately and dividing at the end, which overflows long before the answer does.
- Returning row[0] instead of the last entry of the rolling row.
How to explain it out loud
Fictional example
- Candidate
- Each square can only be reached from above or from the left, so the routes into it are the routes into those two squares added together. The edges have one route each.
- Candidate
- I only need the previous row, so one array of length cols works: each entry adds its left neighbor. That is rows times cols time and cols memory.
- Candidate
- There is also a closed form, since every route is r minus 1 downs mixed into c minus 1 rights. I would use the table if walls might be added later, since the formula cannot handle them.
Related problems
Longest Common Subsequence fills the same kind of grid, but each cell looks at up to three neighbors and takes a maximum. Edit Distance uses that grid again with a minimum and three operations. Starting with this problem makes both easier to read.
Practicing with Natively
Grid problems are easier to explain with a small table drawn first, and that habit is worth rehearsing. In practice, Natively on Mac or Windows can read a grid problem from a screenshot and suggest how to set up the recurrence, so you can compare its approach with your own after you try, and the transcript of your mock helps you spot where you went quiet while filling the table. Learn more about the AI interview assistant.
Questions people ask
How do you solve Unique Paths?
Count routes into each cell: a cell can be entered only from above or from the left, so its count is the sum of those two. The first row and column are 1, and the bottom-right cell holds the answer.
What is the formula for Unique Paths?
Every route is r - 1 down moves and c - 1 right moves in some order, so the count is the binomial coefficient C(r + c - 2, r - 1).
What is the time and space complexity of Unique Paths?
The table takes O(r · c) time. Keeping only one row cuts memory to O(c). The binomial formula needs only O(min(r, c)) multiplications.
How do you count paths when some cells are blocked?
Set the count of a blocked cell to zero and use the same above-plus-left rule everywhere else. The binomial formula no longer applies once walls are added.
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.
