Unique Paths in Java (LeetCode 62): DP Approach
Dynamic Programming (DP) on 2D grids is one of the most common problem patterns in technical coding interviews. The classic problem that introduces this concept is LeetCode 62: Unique Paths.
In this guide, we will break down the problem intuitively, visualize how overlapping subproblems lead to the dynamic programming transition, build an optimized solution, and provide a full Java implementation.
1. Understanding the Problem
There is a robot on an m x n grid. The robot is initially positioned at the top-left corner (grid[0][0]). The robot tries to move to the bottom-right corner (grid[m - 1][n - 1]).
- At each step, the robot can only move either down or right.
- The robot cannot move diagonally or backward.
- Goal: Return the total number of unique paths the robot can take to reach the destination.
Examples
Output: 28
Output: 3
Explanation: From the top-left corner, there are 3 total ways to reach the bottom-right corner:
1. Right → Down → Down
2. Down → Down → Right
3. Down → Right → Down
Prefer Watching? Here is the Video Explanation
int[][] dp = new int[m][n];for (int i = 0; i < m; i++) dp[i][0] = 1; // first column: only 1 wayfor (int j = 0; j < n; j++) dp[0][j] = 1; // first row: only 1 wayfor (int i = 1; i < m; i++) for (int j = 1; j < n; j++) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];return dp[m - 1][n - 1];
2. Core Intuition & Recurrence Relation
To reach any cell (i, j), the robot must arrive from either:
- The cell directly above it:
(i - 1, j)by moving Down. - The cell directly to its left:
(i, j - 1)by moving Right.
Therefore, the total number of unique paths to cell (i, j) is simply the sum of unique paths to reach both of those adjacent cells:
- First row (
i = 0): The robot can only move horizontally to the right. There is only 1 way to reach any cell in the top row:dp[0][j] = 1. - First column (
j = 0): The robot can only move straight down. There is only 1 way to reach any cell in the first column:dp[i][0] = 1.
3. Step-by-Step Grid Dry Run (m = 3, n = 3)
Here is how the 2D DP matrix fills up layer by layer from starting cell (0, 0) to target (2, 2):
| Row / Col | Col 0 | Col 1 | Col 2 |
|---|---|---|---|
| Row 0 | 1 (Start) | 1 | 1 |
| Row 1 | 1 | 2 (1 + 1) | 3 (2 + 1) |
| Row 2 | 1 | 3 (1 + 2) | 6 (Target: 3 + 3) |
Final Answer for 3x3 Grid: 6 unique paths.
4. Java Implementation
Approach: Space-Optimized 1D Dynamic Programming
Notice that calculating any row only requires the values from the current row and the previous row. We can compress the entire 2D matrix into a single 1D array of size n, reducing auxiliary space to O(n):
import java.util.Arrays;
class Solution {
public int uniquePaths(int m, int n) {
// Create a 1D DP array representing values of current row
int[] dp = new int[n];
// Base case: There is 1 path to reach every cell in the first row
Arrays.fill(dp, 1);
// Iterate through remaining rows
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
// dp[j] (new) = dp[j] (from row above) + dp[j - 1] (from left)
dp[j] += dp[j - 1];
}
}
// Last element holds the result for the bottom-right corner
return dp[n - 1];
}
}
5. Complexity Analysis
- Time Complexity:
O(m * n)
We visit every cell in them x ngrid exactly once and perform anO(1)addition operation. - Space Complexity:
O(n)(orO(min(m, n)))
By keeping only a single 1D row array in memory instead of allocating a fullm x nmatrix, we achieve optimal space utilization.
6. Key Takeaways & Common Follow-ups
- Grid DP Pattern: Whenever movement is restricted to Right/Down, the state equation is almost always
dp[i][j] = dp[i-1][j] + dp[i][j-1]. - Space Optimization: Always mention reducing 2D DP to 1D DP during interviews—it demonstrates a deep understanding of memory efficiency.
- Next Challenge: Once you understand this problem, solve LeetCode 63: Unique Paths II (which introduces obstacles) and LeetCode 64: Minimum Path Sum.
Comments
Post a Comment