Count All Valid Pickup and Delivery Options Problem
Description
LeetCode Problem 1359.
Given n orders, each order consists of a pickup and a delivery service.
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 1:
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
Example 2:
Input: n = 2
Output: 6
Explanation: All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
Example 3:
Input: n = 3
Output: 90
Constraints:
1 <= n <= 500
Solution
Approach: Insert One Order at a Time
Let f(i) be the number of valid sequences for i orders. Build the sequences for i orders from those for i - 1.
Look at the last event of a valid sequence of i orders. It must be a delivery (a pickup at the end would have its delivery before it), say of order k. There are i choices for k. Remove D_k and the sequence has 2i - 1 events left, where P_k sits in one of 2i - 1 positions, and the other 2(i - 1) events form a valid sequence for the other i - 1 orders. Every combination of these three choices gives a different valid sequence, and every valid sequence arises once, so
f(i) = i * (2i - 1) * f(i - 1), with f(1) = 1.
Check: f(2) = 2 * 3 * 1 = 6 and f(3) = 3 * 5 * 6 = 90, matching the examples.
(Another way to see the same number: all (2n)! orderings of the events, divided by 2 for each order because exactly half of the orderings put its pickup first: (2n)! / 2n.)
Keep the product modulo 109 + 7 at every step. In Java and C++ use a 64-bit integer, since f * i * (2i - 1) can reach about 5 * 1014. In JavaScript that is still below 253, so ordinary numbers stay exact.
Complexity: O(n) time and O(1) space.
class Solution:
def countOrders(self, n: int) -> int:
mod = 10**9 + 7
ways = 1 # one order: P1 D1
for i in range(2, n + 1):
# Pick which order is delivered last (i ways), then where its pickup goes (2i - 1 slots).
ways = ways * i * (2 * i - 1) % mod
return ways