← DSA
MEDIUM

Unique Paths

PracticeNeetCode ↗LeetCode ↗

A robot sits at the top-left corner of an m x n grid and can only move right or down. Return how many distinct paths it can take to reach the bottom-right corner.

Example

Input m = 3, n = 7
Output 28

Key Pointers

Step-by-Step Analysis

  1. Start with a 1D array row of length n, all 1s (the first row of the grid).
  2. For each subsequent grid row, build a new row where each cell is the cell to its left plus the value above it (from the previous row).
  3. The first cell of every row stays 1, since there's only one way to stay against the left edge.
  4. After processing all m rows, the last value in the final row is the answer.

Complexity

Time: O(m · n) — Space: O(n)

Code

def uniquePaths(m: int, n: int) -> int:
    row = [1] * n
    for _ in range(m - 1):
        new_row = [1] * n
        for c in range(1, n):
            new_row[c] = new_row[c - 1] + row[c]
        row = new_row
    return row[-1]

Code Explanation

How the solution above works, piece by piece.

  1. Every cell in the top row (and left column) can be reached in exactly one way: go straight.
  2. Any other cell is entered from above or from the left: paths(r, c) = paths(r−1, c) + paths(r, c−1).
  3. Only the previous row is needed, so row holds it and new_row is built left to right: new_row[c - 1] is the left neighbour, row[c] the one above.
  4. After m − 1 new rows, row[-1] is the bottom-right count.
  5. O(m × n) time, O(n) space.

Visual Walkthrough

Running it on m = 3, n = 7:

Unique paths grid of size 3 by 701234560111111111234567213610152128each cell = cell above + cell to the leftbottom-right = 28
The robot can only move right or down, so the number of ways to reach a cell is the ways to reach the cell above plus the cell to its left. The first row and column have exactly 1 way. The code keeps only one row at a time.
edge cells = 1answer

Video Explanation

NeetCode — Dynamic Programming, LeetCode 62