Unique Paths medium

Problem Statement

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Example 1:

Input: m = 3, n = 7
Output: 28

Example 2:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Steps

  1. Base Cases: If either m or n is 1, there's only one path.
  2. Recursive Approach (Inefficient): We can recursively explore all possible paths. However, this will lead to significant overlapping subproblems and exponential time complexity.
  3. Dynamic Programming: To avoid redundant calculations, we use dynamic programming. We create a dp array of size m x n where dp[i][j] represents the number of unique paths to reach cell (i, j).
  4. Initialization: The first row and first column will have only one path to reach each cell (either all right moves or all down moves).
  5. Iteration: We iterate through the dp array, calculating the number of paths to reach each cell by summing the paths from the cell above and the cell to the left. dp[i][j] = dp[i-1][j] + dp[i][j-1]
  6. Result: The value at dp[m-1][n-1] represents the total number of unique paths to reach the bottom-right corner.

Explanation

The dynamic programming approach efficiently solves this problem by breaking it down into smaller overlapping subproblems. Instead of recalculating the number of paths to a cell multiple times, we store the result and reuse it. This significantly reduces the time complexity. Each cell's value depends only on its top and left neighbors, allowing for a simple iterative calculation.

Code

function uniquePaths(m: number, n: number): number {
    // Create a DP table
    const dp: number[][] = Array(m).fill(0).map(() => Array(n).fill(0));

    // Initialize the first row and column
    for (let i = 0; i < m; i++) {
        dp[i][0] = 1;
    }
    for (let j = 0; j < n; j++) {
        dp[0][j] = 1;
    }

    // Iterate and fill the DP table
    for (let i = 1; i < m; i++) {
        for (let j = 1; j < n; j++) {
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }

    // The result is at the bottom-right corner
    return dp[m - 1][n - 1];
}

Complexity

  • Time Complexity: O(m * n) - We iterate through the m x n DP table once.
  • Space Complexity: O(m * n) - We use a DP table of size m x n. This could be optimized to O(min(m,n)) by using only a 1D array.