Skip to problem
←

Unique Paths

Medium 0 attempts

A robot starts in the top-left cell of a grid with m rows and n columns. It must reach the bottom-right cell, moving exactly one cell right or down at each step. There are no blocked cells.

Return the number of distinct paths. Paths are different if their sequences of moves differ. The starting and ending cells are included in every path.

A single row or column has one path. A 1 × 1 grid also has one path: stay in the starting cell without making a move. Inputs are guaranteed to have an answer at most 2 × 10^9.

Function contract

Implement uniquePaths(m, n).

Output: Return the number of distinct paths as an integer.

Example 1

Input
m = 3
n = 7
Output
28

Example 2

Input
m = 3
n = 2
Output
3
Visual Aid
Three routes in a 3 × 2 grid
R → D → DD → R → DD → D → R

R means one step right; D means one step down. Every route starts in the top-left cell and ends in the bottom-right cell.

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

One-row dynamic programming

The first row and first column each have one path to every cell. For an interior cell, every path arrives from above or from the left, so add those two counts.

Before updating dp[j], it stores the count from the previous row (above). The already-updated dp[j - 1] stores the count from the current row (left). After the last row, dp[n - 1] is the answer. All intermediate counts fit the stated answer bound.

javascript
function uniquePaths(m, n) {
  const dp = Array(n).fill(1);
  for (let i = 1; i < m; i++)
    for (let j = 1; j < n; j++)
      dp[j] += dp[j-1];
  return dp[n-1];
}

Time: O(mn) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript