Unique Paths
Medium · Dynamic programming
Jump to codeCount paths from the top-left to the bottom-right of an m×n grid, with m,n ≥ 1. Each move goes one cell right or down. There are no obstacles.
Examples
Example 1
m = 3 n = 7
Output: 28
Example 2
m = 3 n = 2
Output: 3
Constraints
- 1 <= m, n <= 100
- The result fits a signed 32-bit integer.
Need a hint?
A cell can be entered only from above or from the left.
Real dynamic programming interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Minimize Branch Merge ConflictsAmazon
- Count Distinct Hat Assignments and Maximize Hat PointsRoblox
- Find and Count Maximum-Score Grid PathsOpenAI
Solution approach
Initialize one row of n counts to one, representing the first row. For each subsequent row, keep its first count one and update each other count by adding its left neighbor. The old value is the contribution from above. Return the last count.
Complexity
O(mn) time and O(n) space.
Python reference solution
def uniquePaths(m, n):
counts = [1] * n
for _ in range(1, m):
for col in range(1, n):
counts[col] += counts[col - 1]
return counts[-1]
JavaScript solution
function uniquePaths(m, n) {
const counts = Array(n).fill(1);
for (let row = 1; row < m; row++) {
for (let col = 1; col < n; col++) counts[col] += counts[col - 1];
}
return counts[n - 1];
}
Java solution
import java.util.*;
class Solution {
public int uniquePaths(int m, int n) {
int[] counts = new int[n];
Arrays.fill(counts, 1);
for (int row = 1; row < m; row++) {
for (int col = 1; col < n; col++) counts[col] += counts[col - 1];
}
return counts[n - 1];
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> counts(n, 1);
for (int row = 1; row < m; row++) {
for (int col = 1; col < n; col++) counts[col] += counts[col - 1];
}
return counts[n - 1];
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 3, 7 ]
28
[ 3, 2 ]
3
[ 1, 1 ]
1
[ 1, 5 ]
1
[ 7, 3 ]
28
Drafts are saved per language in this browser when storage is available.