#1359
Count All Valid Pickup and Delivery Options
HardMathDynamic ProgrammingCombinatoricsDynamic ProgrammingCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to build the count of valid sequences incrementally. Each new order adds combinations based on previous counts, leveraging combinatorial principles.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i] represents the number of valid sequences for i orders.
- 2Step 2: Use the formula dp[i] = dp[i-1] * (2 * i - 1) * i to calculate the number of valid sequences for each i.
- 3Step 3: Return dp[n] modulo 10^9 + 7.
solution.py7 lines
1def countOrders(n):
2 MOD = 10**9 + 7
3 dp = [0] * (n + 1)
4 dp[0] = 1
5 for i in range(1, n + 1):
6 dp[i] = dp[i - 1] * (2 * i - 1) * i % MOD
7 return dp[n]ℹ
Complexity note: The time complexity is O(n) because we compute the valid sequences in a single pass through the DP array, and space complexity is O(n) due to the DP array.
- 1The order of deliveries must always respect the pickup order, leading to a combinatorial structure.
- 2Dynamic programming allows us to build solutions incrementally, reducing the need for exhaustive checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.