Unique Paths

35 min · uniquePaths()

A delivery robot has only two controls: right and down. Even on a modest grid, those two buttons can produce a surprising number of routes.

The robot starts in the top-left cell of an m by n grid. It wants to reach the bottom-right cell, moving exactly one cell right or one cell down at each step. Return the number of distinct paths it can take.

A few ground rules:

  • m is the number of rows and n is the number of columns.
  • The robot stays inside the grid.
  • Two paths are different when their sequences of moves differ.

Constraints

  • 1 <= m, n <= 20
  • The exact path count is less than 2^31.

Hints

Ask how a cell is entered

Except along the top and left edges, a robot can enter a cell from exactly two places: the cell above it or the cell to its left.

Turn that into a rule

If ways[row][col] counts paths into one cell, then it equals the paths into the cell above plus the paths into the cell on the left.

Keep only yesterday's row

While updating one row from left to right, dp[col] still holds the value from above and dp[col - 1] already holds the new value from the left. One row is enough.

Follow-up

Can you derive the same answer by choosing where the down moves appear among all moves, without building a grid at all?

Visible cases

Examples

Example 1

ready
Input
m = 3
n = 7
Expected
28
Why
28 right-and-down move sequences reach the far corner

Example 2

ready
Input
m = 3
n = 2
Expected
3
Why
the single right move can appear before, between, or after the two down moves

Example 3

ready
Input
m = 1
n = 1
Expected
1
Why
the robot is already at its destination

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite