Intuition
The problem can be viewed as moving from the top-left corner of an m × n grid
to the bottom-right corner. Each move must go either down or right,
which means every valid path always consists of (m - 1) downward moves
and (n - 1) rightward moves.
Since the total number of moves is fixed to (m + n - 2), finding the number of unique paths becomes a combinatorial selection problem—we choose which moves are downward (or equivalently, which moves are rightward). This corresponds to the binomial coefficient:
C(m + n - 2, m - 1) = C(m + n - 2, n - 1)
Computation Strategy
- Compute:
- movesDown =
m - 1 - movesRight =
n - 1 - totalMoves =
movesDown + movesRight
- movesDown =
- To optimize computation:
- minMoves =
min(movesDown, movesRight)→ used as the number of iterations. - maxMoves =
max(movesDown, movesRight)→ used as the starting factor in each multiplication (maxMoves + i).
- minMoves =
-
We iterate only minMoves times because the combination formula
C(n, k) = C(n, n - k)is symmetric. Choosing the smaller ofkandn - kminimizes multiplications without affecting the result.
Step-by-Step Calculation
We iteratively compute C(totalMoves, minMoves):
- Initialize result = 1.
- For each
ifrom1tominMoves:- Multiply
resultby(maxMoves + i). - Divide
resultbyi.
- Multiply
Result
After the loop, result holds the number of unique paths in the grid. This iterative approach avoids factorials and large intermediate values, achieving an efficient O(min(m, n)) time and O(1) space solution.