Unique Paths

Pattern: 2D grid DP

medium

To reach a cell moving only right or down, you arrive from above or from the left, so paths(r, c) = paths(r-1, c) + paths(r, c-1). One row of the table is enough.

The problem

A robot moves only right or down on an m × n grid from the top-left to the bottom-right. Return the number of paths. m = 3, n = 7 gives 28.

Think first

  • From which cells can you arrive at (r, c)?
  • How many paths reach a cell in the top row?
  • Is there a formula?

Hints

    Brute force, and why it fails

    Try every path: exponential.

    The key insight

    Each cell's count is the sum of two neighbours' counts, filled row by row.

    Dry run

    row1 1 1 1 1 1 1

    m = 3, n = 7. The top row is all 1s.

    Step 1 of 3

    The plan

    row = [1] * n
    repeat m - 1 times: for c in 1..n-1: row[c] += row[c - 1]
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    One row of counts.

    Edge cases

    • 1 × 1: 1.
    • One row or column: 1.
    • Large grids: use 64-bit or the formula.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int uniquePaths(int m, int n) {
            int[] row = new int[n];                 // ways to reach each cell of the current row
            Arrays.fill(row, 1);                    // the top row: only one way (keep going right)
            for (int r = 1; r < m; r++)
                for (int c = 1; c < n; c++) row[c] += row[c - 1];   // from above (old value) plus from the left
            return row[n - 1];
        }
    }

    C++

    class Solution {
    public:
        int uniquePaths(int m, int n) {
            vector<long long> row(n, 1);            // ways to reach each cell of the current row; the top row has one way
            for (int r = 1; r < m; r++)
                for (int c = 1; c < n; c++) row[c] += row[c - 1];   // from above (old value) plus from the left
            return static_cast<int>(row[n - 1]);
        }
    };

    Python

    class Solution:
        def uniquePaths(self, m: int, n: int) -> int:
            row = [1] * n                           # ways to reach each cell of the current row; the top row has one way
            for _ in range(1, m):
                for c in range(1, n):
                    row[c] += row[c - 1]            # from above (old value) plus from the left
            return row[-1]

    Common mistakes

    • Counting moves instead of paths.
    • Overflow.

    Similar problems