Unique Paths
A robot is located at the top-left corner of an m x n grid. It can only move either right or down at each step. The robot wants to reach the bottom-right corner. How many possible unique paths are there?
This is a classic 2D DP problem. The number of ways to reach cell (i,j) is the sum of ways from above (i-1,j) and from the left (i,j-1): dp[i][j] = dp[i-1][j] + dp[i][j-1]. The base case is dp[0][j] = 1 (only right moves) and dp[i][0] = 1 (only down moves).
The space can be optimized to O(n) by using a single row array that updates left to right: dp[j] += dp[j-1]. This works because dp[j] (above) still holds the value from the previous row before update.
Edge cases include m=1 or n=1 (return 1, only one path along a straight line), and large grids where the result may exceed 32-bit integers.
The combinatorial formula for unique paths is C(m+n-2, m-1) which counts choosing m-1 down moves among m+n-2 total moves. The DP approach is equivalent but builds the solution iteratively, which is easier to understand and extend to problems with obstacles.
The space-optimized version uses a single array where dp[j] is updated left-to-right each row. This works because dp[j] before update represents the value from the row above (dp[i-1][j]), and dp[j-1] after update represents the value from the current row (dp[i][j-1]).
Example Input & Output
1x5: only one path right.
3x7 grid has 28 unique paths.
3x3 grid has 6 paths.
5x1: only one path down.
3x2 grid has 3 paths.
Algorithm Flow

Solution Approach
DP: dp[i][j] = dp[i-1][j] + dp[i][j-1]. Space-optimized to O(n): dp[j] += dp[j-1] for each row.
Time O(m*n), Space O(n).
Best Answers
class Solution {
public int solution(int m, int n) {
int[] dp=new int[n];
for (int j=0;j<n;j++) dp[j]=1;
for (int i=1;i<m;i++) {
for (int j=1;j<n;j++) {
dp[j]+=dp[j-1];
}
}
return dp[n-1];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
