62. Unique Paths
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 2-D Dynamic Programming
- Time
- O(M*N)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven an m x n grid, count the number of distinct paths from the top-left corner to the bottom-right corner, where only rightward and downward moves are allowed.
Approach
- At any cell (r, c), the number of ways to reach it equals the sum of ways from the cell above and the cell to the left, since those are the only two predecessors.
- The top row and left column are base cases: exactly one path reaches any cell along either edge (only one direction of travel is possible).
- We can compress the 2-D DP table to a single 1-D row: iterating left-to-right,
dp[col] += dp[col-1]accumulates the "from-left" contribution in-place whiledp[col](before update) still holds the "from-above" value. - The answer is
dp[n-1]after processing all m rows.
#include <vector>
using namespace std;
class Solution {
public:
int uniquePaths(int m, int n) {
// dp[c] = number of unique paths to reach the current row at column c.
// Initialize to 1: the first row has exactly one path to each cell.
vector<int> dp(n, 1);
// Process rows 1..m-1; row 0 is already handled by the initialization.
for (int r = 1; r < m; ++r) {
// col 0 always has exactly 1 path (move straight down), no update needed.
for (int c = 1; c < n; ++c) {
// dp[c] currently holds "paths from above" (previous row, same col)
// dp[c-1] holds "paths from the left" (same row, previous col, already updated)
dp[c] += dp[c - 1];
}
}
return dp[n - 1];
}
};
Time O(m * n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> res(n, 1);
for(int row=1; row<m; ++row){
for(int col=1; col<n; ++col){
res[col]+=res[col-1];
}
}
return res[n-1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(N) Time O(M*N) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.