Algorithm Day92 - Unique Paths
🧩 Problem Description
A robot is located at the top-left corner of an m x n grid (marked start in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked finish).
How many possible unique paths are there?
💬 Examples
Example 1
1 | Input: m = 3, n = 7 |
Example 2
1 | Input: m = 3, n = 2 |
💡 Intuition
At each cell (i, j), the number of unique paths to reach it is the sum of paths from the top (i-1, j) and from the left (i, j-1). This gives a dynamic programming relation.
Alternatively, this problem has a combinatorial solution using binomial coefficients: choosing (m-1) downs from (m+n-2) total moves.
🔢 Java Code (Dynamic Programming)
1 | class Solution { |
🔢 Java Code (Combinatorics)
1 | class Solution { |
⏱ Complexity Analysis
DP approach:
- Time: O(m × n)
- Space: O(m × n) (can be optimized to O(n))
Combinatorics:
- Time: O(m)
- Space: O(1)
✍️ Summary
- Grid path counting reduces to a classic DP problem.
- Alternatively, solve with binomial coefficient.
- Use combinatorics for very large grids to avoid DP overhead.
Related problems: lc-63 (Unique Paths II), lc-64 (Minimum Path Sum).