62. Unique Paths
Asked at 18Amazon61Bloomberg52Meta52Microsoft50Google49razorpay65Akamai64Flipkart59Qualcomm58Grammarly51EPAM Systems51ByteDance50Nvidia48tcs46Zoho42Goldman Sachs40Visa39TikTok26
Problem
A robot starts at the top-left of an m×n grid and can only move right or down. Count the distinct paths to the bottom-right corner.
Example: m = 3, n = 7 → 28; m = 3, n = 2 → 3
Constraints: m, n ≤ 100; the answer fits in 32 bits.
dp[r][c] = dp[r−1][c] + dp[r][c−1]; one row suffices. (Closed form: C(m+n−2, m−1).)
Complexity: O(m·n) time, O(n) space.
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
row = [1] * n
for _ in range(1, m):
for c in range(1, n):
row[c] += row[c - 1]
return row[-1]
assert Solution().uniquePaths(3, 7) == 28
assert Solution().uniquePaths(3, 2) == 3
class Solution {
public int uniquePaths(int m, int n) {
int[] row = new int[n];
Arrays.fill(row, 1);
for (int r = 1; r < m; r++)
for (int c = 1; c < n; c++) row[c] += row[c - 1];
return row[n - 1];
}
}
func uniquePaths(m int, n int) int {
row := make([]int, n) // paths to each cell of the current row
for c := range row {
row[c] = 1
}
for r := 1; r < m; r++ {
for c := 1; c < n; c++ {
row[c] += row[c-1] // from above (old value) + from the left
}
}
return row[n-1]
}