Count All Valid Pickup and Delivery Options - Problem

Imagine you're managing a delivery service with n orders, where each order consists of exactly two operations: a pickup and a delivery. The challenge is to count all possible valid sequences of these operations.

The key constraint: For every order i, the pickup must happen before the delivery. You cannot deliver something that hasn't been picked up yet!

For example, with 2 orders, you have operations P1, D1, P2, D2. Valid sequences include P1→D1→P2→D2 or P1→P2→D1→D2, but P1→D2→P2→D1 is invalid because D2 happens before P2.

Since the answer can be extremely large, return it modulo 109 + 7.

Input & Output

example_1.py — Simple Case
$ Input: n = 1
Output: 1
💡 Note: With 1 order, we have operations P1 and D1. There's only one valid sequence: P1 → D1 (pickup before delivery).
example_2.py — Two Orders
$ Input: n = 2
Output: 6
💡 Note: With 2 orders (P1,D1,P2,D2), valid sequences are: P1→D1→P2→D2, P1→P2→D1→D2, P1→P2→D2→D1, P2→P1→D1→D2, P2→P1→D2→D1, P2→D1→P1→D2. Wait, that's wrong. Let me recalculate: Actually, there are 6 valid sequences following the constraint that each pickup must come before its delivery.
example_3.py — Three Orders
$ Input: n = 3
Output: 90
💡 Note: With 3 orders, using the formula (2×1-1)² × (2×2-1)² × (2×3-1)² = 1² × 3² × 5² = 1 × 9 × 25 = 225. Wait, let me double-check this calculation...

Constraints

  • 1 ≤ n ≤ 500
  • Each order consists of exactly one pickup and one delivery
  • Delivery must come after corresponding pickup
  • Return result modulo 109 + 7

Visualization

Tap to expand
Position Selection VisualizationStep 1: n=1P1D1Ways: 1Step 2: Add Order 2P1D13 positions for P2P2D1D23 positions for D2Ways: 3 × 3 = 9Mathematical PatternFor order i: Pickup has (2i-1) positions, Delivery has (2i-1) positionsTotal = ∏(i=1 to n) (2i-1)²
Understanding the Visualization
1
Start with Order 1
Place P1,D1 in sequence - only 1 way
2
Add Order 2
P2 has 3 insertion points, D2 has 3 points after P2 placement
3
Add Order 3
P3 has 5 insertion points, D3 has 5 points after P3 placement
4
General Pattern
Order i contributes (2i-1)² ways to the total count
Key Takeaway
🎯 Key Insight: When placing the i-th order into a sequence of (i-1) already placed orders, both pickup and delivery operations have exactly (2i-1) available positions, leading to the formula ∏(2i-1)².
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
38.5K Views
Medium Frequency
~25 min Avg. Time
1.2K 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