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 and Delivery Sequences (n=2)Each delivery must come after its corresponding pickupValid Sequences:P1→P2→D1→D2P1→P2→D2→D1P1→D1→P2→D2P2→P1→D1→D2P2→P1→D2→D1P2→D2→P1→D1Invalid Sequences:D1→P1→P2→D2 ❌P1→D2→P2→D1 ❌D2→P1→P2→D1 ❌Mathematical Pattern Recognitionn=1: 1 sequencen=2: 6 sequencesn=3: 90 sequencesPattern: ∏ i×(2i-1)Result: 6 valid sequences for n=2
Understanding the Visualization
1
Input
n orders, each with pickup Pi and delivery Di
2
Constraint
Every delivery Di must come after pickup Pi
3
Count
Total valid sequences following the constraint
Key Takeaway
🎯 Key Insight: The number of valid sequences follows the mathematical pattern ∏(i=1 to n) i × (2i-1)
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