Skip to content

Unique Paths

Count the routes from the top-left to the bottom-right of a grid when you only move right or down.

Medium2D Dynamic Programming
Solve on LeetCode

The problem

A robot starts in the top-left cell of an m x n grid and wants to reach the bottom-right cell. Each move takes it one cell to the right or one cell down. Return the number of different routes, which you can assume is at most 2 * 10^9.

Input m = 3, n = 3

Output 6

Every route is 2 moves right and 2 moves down in some order: RRDD, RDRD, RDDR, DRRD, DRDR and DDRR.

Input m = 4, n = 5

Output 35

Every route has 4 moves right and 3 moves down, and there are 35 ways to order them.

Key constraint: Both sides are at most 100, so a table of at most 10,000 cells is cheap.

How to spot the pattern

  • You count routes across a grid with moves in only two directions.
  • Each cell can be entered from just two neighbors, the one above and the one to the left.

The idea

State: paths[r][c] is the number of routes from the start to cell (r, c). The last move into a cell comes from above or from the left, so paths[r][c] = paths[r - 1][c] + paths[r][c - 1], and every cell in the top row or left column has exactly 1 route. Each row only needs the row above it, so one array that you update from left to right is enough.

Brute force: Recursively try both moves from every cell without saving results, which takes exponential time.

Step by step

  1. 1Make row of length n filled with 1, the counts for the top row.
  2. 2For each of the remaining m - 1 rows, walk c from 1 to n - 1.
  3. 3Set row[c] += row[c - 1]: the old row[c] is the count from above and row[c - 1] is the count from the left.
  4. 4Return row[n - 1], the count for the bottom-right cell.

See the pattern move

The 2d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        # paths[r][c] = paths[r - 1][c] + paths[r][c - 1]; keep only the current row
        row = [1] * n  # the top row: one way to reach each cell (keep moving right)
        for _ in range(1, m):
            for c in range(1, n):
                row[c] += row[c - 1]  # old row[c] is from above, row[c - 1] is from the left
        return row[n - 1]

Complexity

Time

O(m * n)

Space

O(n)

Every cell is filled once from two neighbors, and only one row is stored.

Watch out for

  • Starting the top row or the left column at 0: each of those cells has exactly 1 route.
  • Using the formula with full factorials, which overflow long before the answer does.

Follow-up questions

Is there a formula?

Yes. A route is an ordering of m - 1 downs and n - 1 rights, so the answer is C(m + n - 2, m - 1). Build it as a running product in a 64-bit integer, dividing at every step, so it stays exact.

What if some cells are blocked?

Give a blocked cell 0 routes and use the same transition everywhere else. That is Unique Paths II.

In Hinglish

Har cell tak aakhri move ya upar se aaya ya left se, toh dono ke paths jod do. Ek row ka array kaafi hai, bas left se right update karte jao.

Related problems