SDE & MLE Prep

62. Unique Paths

Problem

A robot starts at the top-left of an m×n grid and can only move right or down. Count the distinct paths to the bottom-right corner.

Example: m = 3, n = 7 → 28; m = 3, n = 2 → 3

Constraints: m, n ≤ 100; the answer fits in 32 bits.

dp[r][c] = dp[r−1][c] + dp[r][c−1]; one row suffices. (Closed form: C(m+n−2, m−1).)

Complexity: O(m·n) time, O(n) space.

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        row = [1] * n
        for _ in range(1, m):
            for c in range(1, n):
                row[c] += row[c - 1]
        return row[-1]