InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Unique Paths

medium Original ↗ 00:00

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 far too large to enumerate, so 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.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug