#62
Unique Paths
MediumMathDynamic ProgrammingCombinatoricsDynamic ProgrammingCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m+n)) | O(n) |
| Space | O(m+n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages combinatorial mathematics. The robot needs to make exactly (m-1) down moves and (n-1) right moves, regardless of the order. The total number of unique paths can be calculated using combinations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total number of moves required: totalMoves = (m - 1) + (n - 1).
- 2Step 2: Calculate the number of down moves needed: downMoves = m - 1.
- 3Step 3: Use the combination formula C(totalMoves, downMoves) = totalMoves! / (downMoves! * (totalMoves - downMoves)!).
solution.py6 lines
1import math
2
3def uniquePaths(m, n):
4 totalMoves = (m - 1) + (n - 1)
5 downMoves = m - 1
6 return math.comb(totalMoves, downMoves)ℹ
Complexity note: The time complexity is O(n) due to the factorial calculations, but since they can be computed in constant space, the space complexity is O(1).
- 1Understanding the combinatorial nature of the problem can lead to a much more efficient solution.
- 2Recursive solutions can be intuitive but often lead to performance issues with larger inputs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.