Similar Problems
Similar Problems not available
Count All Valid Pickup And Delivery Options - Leetcode Solution
LeetCode: Count All Valid Pickup And Delivery Options Leetcode Solution
Difficulty: Hard
Topics: math dynamic-programming
Problem Statement:
Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
Example:
Input: n = 1 Output: 1 Explanation: Unique order (P1, D1), Delivery follow pickup.
Input: n = 2 Output: 6 Explanation: All possible orders: (P1, P2, D2, D1), (P1, D1, P2, D2), (P1, P2, D1, D2), (P1, D1, D2, P2), (P2, P1, D2, D1), (P2, D2, P1, D1). This is same with permutations of [1,2,3,4] and [2,1,4,3], except that both ([1,2,3,4], [2,1,4,3]) and ([2,1,4,3], [1,2,3,4]) are counted as two.
Input: n = 3 Output: 90
Solution:
The problem seems to be challenging but using a bit of mathematics and by following the problem constraints, we can come up with a general solution.
For the first pickup, we have n
options for the first pickup, since there are n
orders. Then for the second pickup, we again have n-1
options left to choose from.
For the first delivery, we have 2 options, we can choose it after the first pickup or after the second pickup. Then for the second delivery, we also have two options, we can choose it after the remaining pickup or after the remaining delivery. Same goes for the remaining pickups and deliveries.
Now, in general, we have n
choices for the first pickup, n-1
choices for the first delivery, n-2
choices for the second pickup, n-3
choices for the second delivery, and so on, until we have only one left for the last pickup.
Therefore, the answer will be the product of n, n-1, n-2, …, 2, 1, which is n factorial (n!). But since the order of the pickups and deliveries does not matter, we have to divide by the number of ways to arrange the pickups and deliveries, which is (n!) / (2^n).
Hence, the final answer will be n!/(2^n).
Finally, we need to take the answer modulo 10^9 + 7.
The python code for this solution will be:
class Solution:
def countOrders(self, n: int) -> int:
return math.factorial(n) // (2 ** n) % (10 ** 9 + 7)
Time Complexity: O(1)
Space Complexity: O(1)
Count All Valid Pickup And Delivery Options Solution Code
1