LeetCode 1359. Count All Valid Pickup and Delivery Options

Question

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

1
2
3
4
5
6
7
8
9
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.

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.

Solution

We assumed it already have n - 1 pair, and we have to place the final pair. The number of we can place is 2 * (n - 1) + 1 = 2*n - 1, so for the last, it should be 2 * n, which add one more section we can use due to the operation.

Code

1
2
3
4
5
6
7
8
9
// time:O(n), space:O(1)
public int countOrders(int n) {
long res = 1;
int mod = (int) Math.pow(10, 9) + 7;
for (int i = 1; i <= n; i++) {
res = res * (2 * i - 1) * i % mod;
}
return (int) res;
}