Count All Valid Pickup and Delivery Options - Problem

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 pickup(i).

Since the answer may be too large, return it modulo 10^9 + 7.

Example: If n=1, we have one order. The valid sequences are: [P1, D1]. Answer = 1.

Example: If n=2, we have two orders. Valid sequences include: [P1, P2, D1, D2], [P1, P2, D2, D1], [P1, D1, P2, D2], [P2, P1, D1, D2], [P2, P1, D2, D1], [P2, D2, P1, D1]. Answer = 6.

Input & Output

Example 1 — Single Order
$ Input: n = 1
Output: 1
💡 Note: With 1 order, we have one pickup P1 and one delivery D1. The only valid sequence is [P1, D1], so the answer is 1.
Example 2 — Two Orders
$ Input: n = 2
Output: 6
💡 Note: With 2 orders, valid sequences are: [P1,P2,D1,D2], [P1,P2,D2,D1], [P1,D1,P2,D2], [P2,P1,D1,D2], [P2,P1,D2,D1], [P2,D2,P1,D1]. Total = 6.
Example 3 — Three Orders
$ Input: n = 3
Output: 90
💡 Note: With 3 orders, following the pattern: 1 × 1 × 2 × 3 × 3 × 5 = 90 valid sequences where each delivery comes after its pickup.

Constraints

  • 1 ≤ n ≤ 500
  • Answer fits in 32-bit integer after taking modulo 109 + 7

Visualization

Tap to expand
Valid Pickup & Delivery Sequences INPUT Order 1 P1 D1 n = 1 Single order with pickup P1 and delivery D1 CONSTRAINT: D(i) must come after P(i) ALGORITHM STEPS 1 Base Case For n=1: only [P1, D1] 2 Formula Pattern f(n) = f(n-1) * (2n-1) * n 3 Count Slots Insert new pair in gaps 4 Apply Modulo Result mod 10^9 + 7 For n=1: P1 D1 = 1 way Only valid sequence P1 before D1 FINAL RESULT Output: 1 return 1 Valid sequences: [P1, D1] Total: 1 sequence OK Key Insight: For n orders, we insert each new pickup-delivery pair into existing sequence. With 2(n-1) items, there are (2n-1) slots for pickup and n valid positions for delivery after pickup. Formula: f(n) = f(n-1) * (2n-1) * n, with f(1) = 1. Time: O(n), Space: O(1) TutorialsPoint - Count All Valid Pickup and Delivery Options | Optimal Solution
Asked in
Google 15 Amazon 12 Facebook 8
25.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen