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 <= 500This approach leverages recursion with memoization to calculate the number of valid sequences. The main idea is to determine how many ways we can arrange pickups and deliveries by handling one order at a time.
This Python function uses a recursive helper function dp(p, d) that tracks how many pickups and deliveries are remaining. If both pickups and deliveries are zero, it returns 1 as a valid sequence is formed. Otherwise, it calculates the possible sequences either by picking up an order or delivering an order, avoiding violating the sequence rule.
Java
Time Complexity: O(N^2), where N is the number of orders, due to overlapping subproblems.
Space Complexity: O(N^2) due to storing results in the memoization dictionary.
This approach uses a combinatorial method by calculating factorial operations iteratively to compute the number of valid sequences. It simplifies the problem by deriving a general formula.
This C++ solution iteratively applies a combinatorial formula that derives from possible positioning of deliveries after pickups. It computes using factorial increases corresponding to the number of current orders.
JavaScript
Time Complexity: O(N), where N is the number of orders.
Space Complexity: O(1), as we only maintain a constant amount of extra space.
| Approach | Complexity |
|---|---|
| Recursive Approach with Memoization | Time Complexity: O(N^2), where N is the number of orders, due to overlapping subproblems. |
| Iterative Approach with Combinatorics | Time Complexity: O(N), where N is the number of orders. |
Count all Valid Pickup and Delivery Options - Leetcode 1359 - Python • NeetCodeIO • 10,946 views views
Watch 9 more video solutions →Practice Count All Valid Pickup and Delivery Options with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor