InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Unique Paths

medium Original ↗
Solving tips
  • Archetypal monotone grid DP: dp[i][j] = dp[i-1][j] + dp[i][j-1], since each cell is reached only from above or the left.
  • The first row and first column are all 1 (a single straight-line route reaches them); don't overwrite these base cases when looping.
  • Target O(m*n) time, O(n) space with a single rolling array (row[j] += row[j-1]).
  • Bonus: there is an O(min(m,n)) combinatorics shortcut, C(m+n-2, m-1), but the DP generalizes when obstacles or weights are added.

Problem

A robot sits in the top-left cell of an m × n grid. At each step it may move only right or down by one cell. Count how many distinct paths it can take to reach the bottom-right cell.

Examples

  • m = 3, n = 728 — all monotone right/down routes across a 3-row, 7-column grid.
  • m = 3, n = 23 — the three routes are DDR, DRD, RDD.
  • m = 1, n = 11 — start equals finish; the empty path counts once.

Constraints

  • 1 <= m, n <= 100
  • The answer is guaranteed to fit in a 32-bit signed integer.
  • With a 100×100 grid the number of paths is astronomically large, so you cannot enumerate them — you need an O(m·n) counting method.

Think about it first

Hint 1 To arrive at a cell you either came from the cell directly above it or the cell directly to its left. So the count of paths into a cell is the sum of the counts into those two neighbors.
Hint 2 Cells in the first row have exactly one path (all rights); cells in the first column have exactly one path (all downs). These are your base cases: `dp[0][j] = dp[i][0] = 1`.
Hint 3 `dp[i][j] = dp[i-1][j] + dp[i][j-1]`. Since each row only needs the row above, you can compute in place with a single array of length `n`. (There is also a pure combinatorics shortcut — the path is a sequence of `m-1` downs and `n-1` rights.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.