Skip to main content
59

Unique Paths

Mediumdynamic programmingmatrix

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:2-D Dynamic ProgrammingRead the beginner guide

A robot stands in the top-left cell of an m x n grid and wants to reach the bottom-right cell. It can only move right or down, one cell at a time.

Return the number of distinct paths it can take.

Understand the problem

  • The grid has m rows and n columns.
  • The robot can never move up or left, so it can't go back.
  • Two paths are different if they differ in at least one move.

Example 1

text
Input:  m = 3, n = 2
Output: 3

The three paths: right → down → down, down → right → down, down → down → right.

Example 2

text
Input:  m = 3, n = 7
Output: 28

Example 3

text
Input:  m = 1, n = 5
Output: 1

A single row: the only path is right, right, right, right.

Constraints

  • 1 <= m, n <= 100
  • The answer is at most 2 * 10^9.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The number of paths into a cell is the number of paths into the cell above it plus the number into the cell to its left, so fill the grid from the top-left corner and read the answer from the bottom-right one.

    The naive approach (and why it's slow)

    Recursively try both moves from every cell. A path is m + n - 2 moves long, and each move has two choices, so this explores up to about 2^(m+n) paths. For a 100 x 100 grid, that's hopeless.

    From one dimension to two

    In 1-D DP, each answer was for a position in a line. Here the robot's position is a cell (r, c), so the saved answers form a grid: that's what "2-D DP" means.

    The key insight: look at the last move

    The robot's last move into cell (r, c) was either:

    • down, from the cell above: (r - 1, c), or
    • right, from the cell to the left: (r, c - 1).

    Every path into (r, c) comes through exactly one of these, so:

    text
    paths[r][c] = paths[r - 1][c] + paths[r][c - 1]

    Base cases: every cell in the first row or the first column has exactly 1 path (go straight right, or straight down).

    Step by step

    m = 3, n = 4. Each cell is the one above plus the one to the left:

    text
    1   1   1   1
    1   2   3   4
    1   3   6  10

    For example, the middle 3 (row 1, column 2) = 1 (above) + 2 (left). The bottom-right cell holds the answer: 10.

    Saving memory: one row is enough

    Each row only uses the row above it. So keep a single array row of length n, starting as all 1s (the first row), and update it left to right for each new row:

    • Before updating, row[c] still holds the value from above.
    • row[c - 1] was just updated, so it holds the new value from the left.

    So row[c] += row[c - 1] is the whole recurrence:

    After rowrow
    0[1, 1, 1, 1]
    1[1, 2, 3, 4]
    2[1, 3, 6, 10]

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(m · n). Each cell is computed once.
    • Memory: O(n) with the single row (O(m · n) with the full grid).

    Common mistakes

    • Setting the first row/column to 0. They're 1: there's exactly one straight path.
    • Mixing up m (rows) and n (columns). The answer happens to be the same either way, but in a grid with obstacles it isn't.
    • Recursing without saving answers. Exponential.

    Going deeper

    • Math shortcut: every path is exactly m - 1 downs and n - 1 rights in some order, so the answer is "choose which of the m + n - 2 moves are downs": the binomial coefficient C(m + n - 2, m - 1). Nice to mention, but interviewers want the DP, because it extends to harder versions.
    • Unique Paths II adds obstacles: a blocked cell has 0 paths, and the same recurrence works for everything else.
    • Minimum Path Sum uses the same grid, but takes the min of above and left plus the cell's cost.

    Reference solution

    js
    /**
     * @param {number} m
     * @param {number} n
     * @return {number}
     */
    export default function uniquePaths(m, n) {
      // One row of the grid at a time. The first row is all 1s: one straight path to each cell.
      const row = new Array(n).fill(1)
      for (let r = 1; r < m; r++) {
        // row[0] stays 1 (first column). For the rest:
        // row[c] (still the value from ABOVE) + row[c - 1] (already updated: from the LEFT).
        for (let c = 1; c < n; c++) row[c] += row[c - 1]
      }
      return row[n - 1] // the bottom-right cell
    }
    ts
    export default function uniquePaths(m: number, n: number): number {
      // One row of the grid at a time. The first row is all 1s: one straight path to each cell.
      const row = new Array<number>(n).fill(1)
      for (let r = 1; r < m; r++) {
        // row[0] stays 1 (first column). For the rest:
        // row[c] (still the value from ABOVE) + row[c - 1] (already updated: from the LEFT).
        for (let c = 1; c < n; c++) row[c] += row[c - 1]
      }
      return row[n - 1] // the bottom-right cell
    }
    python
    def unique_paths(m: int, n: int) -> int:
        # One row of the grid at a time. The first row is all 1s: one straight path to each cell.
        row = [1] * n
        for _ in range(1, m):
            # row[0] stays 1 (first column). For the rest:
            # row[c] (still the value from ABOVE) + row[c - 1] (already updated: from the LEFT).
            for c in range(1, n):
                row[c] += row[c - 1]
        return row[-1]  # the bottom-right cell