Taro Logo

Unique Paths

#164 Most AskedMedium
Topics:
Dynamic Programming

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 109.

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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

Constraints:

  • 1 <= m, n <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum values for the number of rows and columns ($m$ and $n$), and could the result exceed the limits of a standard 32-bit or 64-bit integer?
  2. What should be returned if $m$ or $n$ is less than 1 (e.g., a $0 imes 0$ or $1 imes 0$ grid)?
  3. Are there any obstacles or blocked cells in the grid, or is every intermediate cell always traversable?
  4. Can the robot move in any other directions besides right and down, such as diagonally or upwards, if needed?
  5. Should we optimize for time complexity or space complexity, given that this can be solved in $O(min(m, n))$ space?

Brute Force Solution

Approach

Imagine you are standing at the top-left corner of a grid and need to walk to the bottom-right corner, only ever moving right or down. The brute force approach involves physically walking every single possible path from start to finish to see how many valid routes exist.

Here's how the algorithm would work step-by-step:

  1. Begin your journey at the starting square in the top-left corner.
  2. At every single square you visit, pause and ask yourself if you can move to the right and if you can move downwards.
  3. If moving to the right is an option, take that path and follow it all the way to the end, making every subsequent choice step-by-step.
  4. If you hit a dead end or reach the bottom-right corner, retrace your steps back to the last split in your journey.
  5. Once you are back at that split, try the downward path instead, again following it completely to see where it leads.
  6. Keep track of every single time you successfully reach the bottom-right corner by counting that journey as one complete path.
  7. Continue exploring every possible branch, turn, and combination of right and down movements until literally every single route has been walked at least once.

Code Implementation

def unique_paths(grid_rows, grid_columns):
    def explore_paths(current_row, current_column):
        # Base case to count a successful complete journey when the destination is reached
        if current_row == grid_rows - 1 and current_column == grid_columns - 1:
            return 1

        # Stop exploring further if we move outside the grid boundaries
        if current_row >= grid_rows or current_column >= grid_columns:
            return 0

        # Branch into both valid directions to explore every possible route to the end
        paths_going_right = explore_paths(current_row, current_column + 1)
        paths_going_down = explore_paths(current_row + 1, current_column)

        return paths_going_right + paths_going_down

    return explore_paths(0, 0)

Big(O) Analysis

Time Complexity
O(2^(m+n)) – Starting from the top-left corner of a grid with m rows and n columns, the brute force approach makes a binary choice at nearly every square to either move right or move down. Because every single valid route is explored by recursively branching into these two directions, the number of total paths doubles with each step taken across the grid. This exhaustive traversal leads to roughly two to the power of m plus n total recursive operations. Simplifying this exponential growth relative to the grid dimensions results in a time complexity of O(2^(m+n)).
Space Complexity
O(min(m, n)) – The space complexity is driven by the recursion stack and temporary storage used while exploring every branch, turn, and combination of right and down movements. As described in the plain English steps, retracing paths back to the last split requires maintaining stack frames that grow proportionally to the grid dimensions. Specifically, the maximum depth of the recursion tree corresponds to the shortest path to reach the bottom-right corner, which is bounded by the smaller dimension of the grid, denoted as N. Therefore, the auxiliary memory consumed by these active execution paths scales linearly with N, leading to a space complexity of O(min(m, n)).

Optimal Solution

Approach

Instead of exploring every possible path from start to finish, the optimal approach works backward from the destination by adding up the known paths from previous steps. This prevents repeating the same work and instantly solves the puzzle by recognizing that the number of ways to reach any spot is simply the sum of the ways to reach the spot directly above it and the spot directly to its left.

Here's how the algorithm would work step-by-step:

  1. Imagine standing at the very end of the grid where the destination is, knowing there is exactly one way to be finished when you are already there.
  2. Look at the squares immediately to the left and directly above the finish line, realizing that each of them also has only one direct path remaining to reach the end.
  3. Move backward through the entire grid row by row, filling in each square with a number that represents the total number of ways to reach the end from that specific spot.
  4. Calculate the value for any given square by taking the sum of the value to its right and the value below it, since those are the only two directions you could have traveled from.
  5. Continue this backward calculation all the way until you reach the starting square at the opposite corner.
  6. Read the final number sitting at the starting square, which instantly tells you the total number of unique paths possible without ever having to walk a single step.

Code Implementation

class Solution:
    def uniquePaths(self, number_of_rows: int, number_of_cols: int) -> int:
        # Initialize a grid with ones to represent the base paths at the edges.
        path_counts = [[1] * number_of_cols for _ in range(number_of_rows)]

        # Iterate backward from the bottom-right corner to accumulate path counts.
        for row_index in range(number_of_rows - 2, -1, -1):
            for col_index in range(number_of_cols - 2, -1, -1):
                # Sum paths from the right and below to find total ways from current spot.
                path_counts[row_index][col_index] = path_counts[row_index + 1][col_index] + path_counts[row_index][col_index + 1]

        return path_counts[0][0]

Big(O) Analysis

Time Complexity
O(m * n) – The time complexity is driven by traversing every cell in the m by n grid during the backward calculation from the destination to the starting square. For each of the m rows, the algorithm visits each of the n columns to compute the sum of the adjacent cells to the right and below. This requires m multiplied by n total operations, which simplifies to the Big O time complexity of O(m * n).
Space Complexity
O(n) – To optimize the space while moving backward through the grid as described in the explanation, we can maintain a single auxiliary array representing just one row or column of the grid instead of a full two-dimensional table. As the input grid dimensions grow with N, this rolling array requires extra memory proportional to the smaller dimension of the grid to store intermediate path sums. By continuously updating this single-row data structure in place, we avoid storing the entire grid history. Consequently, the auxiliary space complexity simplifies to Big O of N, where N represents the number of columns in the grid.

Edge Cases

Grid with only one row or one column (m=1 or n=1)
How to Handle:
The DP algorithm naturally initializes and computes a single path since only one direction of movement is possible.
Minimum possible grid size of 1x1
How to Handle:
The solution immediately returns 1 since the robot is already at the destination.
Large grid dimensions causing integer overflow
How to Handle:
Using 64-bit integers (long in Java or standard int in Python which handles arbitrarily large integers) prevents arithmetic overflow for large results.
Deep recursion causing stack overflow in a naive recursive approach
How to Handle:
Using bottom-up dynamic programming or memoization limits the call stack depth and prevents stack overflow errors.
Extremely large grid dimensions causing memory limit exceeded
How to Handle:
Optimizing space complexity from a 2D matrix to a 1D array reduces memory usage to O(n) space.
Asymmetric grids where rows are much greater than columns or vice versa
How to Handle:
Iterating through the full dimensions correctly computes all state transitions regardless of grid aspect ratio.
0/245 completed