Unique Paths

medium
math
dynamic-programming
combinatorics

A robot sits in the top-left cell of an m x n grid and wants to reach the bottom-right cell. It may only move right or down one cell at a time. Return how many distinct paths it can take.

Input / output

  • Input: m: integer (rows), n: integer (columns)
  • Output: the number of unique paths

Examples

  1. m = 3, n = 7 returns 28.
  2. m = 3, n = 2 returns 3.
  3. m = 1, n = 1 returns 1.

Constraints

  • 1 <= m, n <= 100
  • The answer is guaranteed to fit in a 32-bit signed integer.

Follow-up Can you solve it in O(min(m, n)) space using the closed-form binomial coefficient C(m + n - 2, m - 1) instead of a full DP table?

Examples

Example 1

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

Example 2

Input: m = 3, n = 2
Output: 3

Example 3

Input: m = 1, n = 1
Output: 1
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.