
Problem
Solution
Submissions
Unique Paths in Grid
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Java program to find the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid. You can only move either down or right at any point in time.
Example 1
- Input:
- m = 3
- n = 7
- Output: 28
- Explanation:
- Step 1: Create a 3×7 grid where each cell will store the number of unique paths to reach that cell.
- Step 2: Initialize the first row and first column of the grid to 1, since there's only one way to reach any cell in the first row or first column.
- Step 3: For each remaining cell (i,j), the number of ways to reach it is the sum of ways to reach the cell above it (i-1,j) and the cell to its left (i,j-1).
- Step 4: Apply the formula: dp[i][j] = dp[i-1][j] + dp[i][j-1] for all cells.
- Step 5: The value in the bottom-right cell dp[2][6] gives the total number of unique paths: 28.
Example 2
- Input:
- m = 3
- n = 2
- Output: 3
- Explanation:
- Step 1: Create a 3×2 grid where each cell will store the number of unique paths to reach that cell.
- Step 2: Initialize the first row and first column of the grid to 1.
- Step 3: For each remaining cell, apply the formula: dp[i][j] = dp[i-1][j] + dp[i][j-1].
- Step 4: The three unique paths from the top-left (0,0) to bottom-right (2,1) are: - Right, Down, Down - Down, Right, Down - Down, Down, Right
- Step 5: The value in the bottom-right cell dp[2][1] gives the total number of unique paths: 3.
Constraints
- 1 ≤ m, n ≤ 100
- It's guaranteed that the answer will be less than or equal to 2 * 10^9
- Time Complexity: O(m * n)
- Space Complexity: O(m * n) or O(n) with space optimization
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use dynamic programming to solve this problem
- Create a 2D array dp where dp[i][j] represents the number of unique paths to reach position (i,j)
- Initialize the first row and first column of dp to 1 since there's only one way to reach any cell in the first row or first column
- For other cells, the number of ways to reach dp[i][j] is dp[i-1][j] + dp[i][j-1]
- Return dp[m-1][n-1] as the final answer
- Optimization: You can reduce the space complexity to O(n) by using a 1D array