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 Published 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.

A 4 by 4 grid made up for this page (1 = blocked)
col 0col 1col 2col 3
row 00000
row 10100
row 20001
row 31000
A 4 by 4 grid made up for this page (1 = blocked). Scroll sideways on a small screen.

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 explores every route; adding a cache turns it into O(rows × cols).

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]
O(rows × cols) time, O(cols) extra memory.
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];
}
The same loop in JavaScript.

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

Contents of row after each grid row is processed (printed by the code)
After rowcol 0col 1col 2col 3What happened
01111Only one way along the open top edge
11012Block at col 1 zeroes it; col 3 gets 1 from above + 1 from left
21120Block at col 3 zeroes it
30133Block at col 0; the finish collects 3 from the left, 0 from above
Contents of row after each grid row is processed (printed by the code). Scroll sideways on a small screen.

Cost

Time and memory, R rows and C columns
ApproachTimeExtra memory
Walk every routeExponential in R + CO(R + C) recursion
Memoized recursionO(R × C)O(R × C) cache + O(R + C) stack
Full 2D tableO(R × C)O(R × C)
One row (above)O(R × C)O(C)
Time and memory, R rows and C columns. Scroll sideways on a small screen.

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

Getting from recursion to one row
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.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP