CodeArchon

medium2-D Dynamic ProgrammingGoogleFacebook

Grid Path Counter

A delivery robot in an m×n warehouse walks only right or down; count all distinct corner-to-corner routes.

Given m rows and n columns, return the number of unique paths from the top-left to the bottom-right if you can only move right or down.

Choose approach

1
1
1
1
1
?
?
?
1
?
?
?
1/8
Narrationstep 1 of 8

Seed first row/column with 1 (unique path to edge).

1def uniquePaths(m, n):
2 dp = [[1]*n for _ in range(m)]
3 for r in range(1, m):
4 for c in range(1, n):
5 dp[r][c] = dp[r-1][c] + dp[r][c-1]
6 return dp[m-1][n-1]
Variables
m=3
n=4

How to think about it

  1. Equivalent to C(m+n-2, m-1).
  2. Can be reduced to O(n) rolling row.

Edge cases to catch in interview

  • 1×n or m×1 -> 1.
  • Very large m,n -> use binomial coefficient.

Examples

Example 128
{"m":3,"n":7}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed