Unique Paths
Master this topic with zero to advance depth.
Unique Paths
There is a robot on an m x n grid. The robot is initially located at the top-left corner (grid[0][0]). The robot tries to move to the bottom-right corner (grid[m-1][n-1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
Visual Representation
m=3, n=2
Grid:
(S) (1) (S=Start, E=End)
(1) (1)
(1) (E)
Paths:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Total: 3Examples
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
- Right -> Down -> Down
- Down -> Down -> Right
- Down -> Right -> Down
Level I: Dynamic Programming (2D)
Intuition
The number of ways to reach cell (i, j) is the sum of ways to reach the cell above it (i-1, j) and the cell to its left (i, j-1).
Thought Process
dp[i][j] = dp[i-1][j] + dp[i][j-1].- Base cases:
dp[0][j] = 1anddp[i][0] = 1because there is only one way to move along the edges (straight right or straight down).
Detailed Dry Run
m=3, n=3
| Row | Col 0 | Col 1 | Col 2 | Action |
|---|---|---|---|---|
| 0 | 1 | 1 | 1 | Init Row 0 |
| 1 | 1 | 2 | 3 | 1+1=2, 2+1=3 |
| 2 | 1 | 3 | 6 | 1+2=3, 3+3=6 |
Level II: Memoization (Top-Down Recursion)
Intuition
The recursive brute force for grid path counting has overlapping subproblems. We cache each (i, j) state so we never recompute it.
Visual
Memo Grid (m=3, n=3):
| 0 | 1 | 1 |
| 1 | 2 | ? | <- memo[1][2] reused by (2,2)
| 1 | ? | ? |Detailed Dry Run
m=3, n=3. memo[2][2] = memo[1][2] + memo[2][1]. Both sub-calls are cached after first computation.
Level III: Space Optimized (1D)
Intuition
To compute dp[i][j], we only need the value above it dp[i-1][j] (from the previous row) and the value to its left dp[i][j-1] (already computed in the current row). We can use a single row array.
Logic Steps
- Initialize a
rowarray of sizenwith 1s. - Iterate
m-1times (for all rows except the first). - For each row, iterate through columns 1 to
n-1:row[j] = row[j] + row[j-1].
- Return
row[n-1].
Detailed Dry Run
m=3, n=3
| Action | row array |
|---|---|
| Init | [1, 1, 1] |
| Row 1 | [1, (1+1)=2, (2+1)=3] |
| Row 2 | [1, (1+2)=3, (3+3)=6] |
⚠️ Common Pitfalls & Tips
Ensure the loop for columns starts at 1, as the first column always has 1 path (staying at the left edge).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.