Unique Paths

Difficulty: Medium

A robot starts at the top-left corner of an m x n grid and moves only right or down, one cell at a time. Count the distinct paths to the bottom-right corner.

Examples

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

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

Right-Down-Down, Down-Right-Down, and Down-Down-Right.

Constraints

  • 1 <= m, n <= 100

Approach

The robot can only reach a cell from the cell above or the cell to the left. So the ways to reach a cell are the sum of the ways to reach those two.

Build a table of "ways to reach this cell", starting at the top-left (1 way: don't move) and filling rows left to right, top to bottom, using only values already computed.

Solutions

Brute Force — Recursion

From any cell, recursively add the paths from moving right and from moving down. Correct, but recomputes the same cells many times.

function uniquePaths(m, n) {
  function countFrom(row, col) {
    if (row === m - 1 || col === n - 1) return 1;
    return countFrom(row + 1, col) + countFrom(row, col + 1);
  }
  return countFrom(0, 0);
}

Time: O(2^(m+n)) · Space: O(m + n) — recursion depth

Optimal — Bottom-Up 2D Table

Build a grid of ways to reach each cell. The first row and column are 1 (one way to reach each), and every other cell is the sum of the cell above and the cell to the left.

function uniquePaths(m, n) {
  const table = Array.from({ length: m }, () => new Array(n).fill(1));

  for (let row = 1; row < m; row++) {
    for (let col = 1; col < n; col++) {
      table[row][col] = table[row - 1][col] + table[row][col - 1];
    }
  }

  return table[m - 1][n - 1];
}

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