Unique Paths - Combinatorial JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

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
  • 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).
  • We iterate only minMoves times because the combination formula C(n, k) = C(n, n - k) is symmetric. Choosing the smaller of k and n - k minimizes multiplications without affecting the result.

Step-by-Step Calculation

We iteratively compute C(totalMoves, minMoves):

  • Initialize result = 1.
  • For each i from 1 to minMoves:
    • Multiply result by (maxMoves + i).
    • Divide result by i.

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.

Time Complexity

Let m be the number of rows and n be the number of columns in the grid. Then minMoves = min(m - 1, n - 1). The algorithm evaluates the binomial coefficient by looping i = 1..minMoves, performing constant work (O(1)) in each step. Therefore, the overall time complexity is O(min(m, n)).

Space Complexity

The algorithm runs in O(1) space, using only a few scalar variables.

Visucodize editorial solution titled Combinatorial JS Solution for LeetCode's Unique Paths coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/unique-paths.