Talentd
FleetCode
Make and follow sheets.Sign in

Count All Valid Pickup and Delivery Options solution and explanation

HardCombinatoricsDynamic ProgrammingMath5 min read64.9% acceptanceUpdated 9 Apr 2026
Count all Valid Pickup and Delivery Options - Leetcode 1359 - PythonNeetCodeIO · 9:15 · 12K viewsWatch on YouTube
9 more videos on this problem
  1. Count all Valid Pickup and Delivery Options - Leetcode 1359 - PythonNeetCodeIO · 9:15 · 12K views
  2. Count All Valid Pickup and Delivery Options | Leetcode 1359 | Easy DP | Live coding session 🔥🔥Coding Decoded · 12:24 · 5K views
  3. 1359. Count All Valid Pickup and Delivery Options II Math II Permutation and CombinationAryan Mittal · 13:40 · 3K views
  4. Count All Valid Pickup and Delivery Options | Leetcode 1359 | Math | Day-6Ayushi Sharma · 22:39 · 3K views
  5. count all valid pickup and delivery options | Leetcode 1359Tech Adora by Nivedita · 5:37 · 1K views
  6. Count All Valid Pickup and Delivery Options | Dynamic Programming | 1359 LeetCode | Day 06CodeWithSunny · 18:50 · 1K views
  7. Dynamic Programming Recursion Math 3-in-1 LeetCode 1359 Count All Valid Pickup and Delivery OptionsvanAmsen · 13:01 · 920 views
  8. Count All Valid Pickup and Delivery Options | Leetcode | 1359Pessimist Programmer · 5:03 · 588 views
  9. Daily Leetcode #1258: Sep 10, 2023 - 1359. Count All Valid Pickup and Delivery OptionsProgramming Live with Larry · 13:56 · 410 views
  10. Count All Valid Pickup and Delivery Options | DP |Daily Leetcode Challenge | Leetcode 1359 | HardLet's Code Together · 13:35 · 295 views

The 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 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 <= 500

Approach overview

Problem Overview: Given n pickup and delivery orders, count how many valid sequences exist such that each delivery D_i happens only after its corresponding pickup P_i. The answer grows quickly, so results are returned modulo 1e9 + 7. The challenge is counting valid permutations while respecting ordering constraints.

Approach 1: Recursive Dynamic Programming with Memoization (Time: O(n^2), Space: O(n^2))

This method models the process using two variables: remaining pickups and remaining deliveries. At any step, you can place a pickup if any remain, or place a delivery if its pickup has already been used. The recursive state dp(p, d) represents the number of valid sequences with p pickups and d deliveries left. Each state branches into placing a pickup (p choices) or a valid delivery (d - p choices because those pickups are already done). Memoization stores computed states to avoid repeated work. This approach clearly shows the combinatorial structure and works well for learning recursion and dynamic programming.

Approach 2: Iterative Combinatorics Formula (Time: O(n), Space: O(1))

A mathematical observation leads to a much simpler solution. When adding the i-th order, there are 2i - 1 possible positions to insert the delivery relative to the pickup while preserving validity. The number of ways to place the pickup among current slots gives i choices, producing the recurrence f(i) = f(i-1) * i * (2i - 1). Iterating from 1 to n and multiplying these terms builds the result efficiently. This converts the counting problem into a direct formula using ideas from math and combinatorics. Only a running product and modulo operations are required.

Recommended for interviews: The combinatorics iteration is the expected optimal solution. It runs in O(n) time with constant space and shows strong pattern recognition. The recursive DP approach is still valuable during discussion because it demonstrates how to model constraints with state transitions before simplifying the counting mathematically.

Approach 1: Recursive Approach with Memoization

This 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.

MOD = 10**9 + 7

def countOrders(n):
    memo = {}
    
    def dp(p, d):
        if p == 0 and d == 0:
            return 1
        if (p, d) in memo:
            return memo[(p, d)]
        
        ways = 0
        if p > 0:
            ways += p * dp(p - 1, d + 1)
        if d > 0:
            ways += d * dp(p, d - 1)
        
        memo[(p, d)] = ways % MOD
        return ways % MOD
    
    return dp(n, 0)
class Solution {
    private static final int MOD = 1000000007;
    
    public int countOrders(int n) {
        int[][] dp = new int[n + 1][n + 1];
        dp[0][0] = 1;
        
        for (int p = 0; p <= n; ++p) {
            for (int d = 0; d <= n; ++d) {
                if (p < n) {
                    dp[p + 1][d] = (dp[p + 1][d] + (long)(n - p) * dp[p][d]) % MOD;
                }
                if (p > d) {
                    dp[p][d + 1] = (dp[p][d + 1] + (long)(p - d) * dp[p][d]) % MOD;
                }
            }
        }
        
        return dp[n][n];
    }
}

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.

Complexity

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.

Try this approach in the editor

Approach 2: Iterative Approach with Combinatorics

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.

#include <vector>
using namespace std;

const int MOD = 1e9 + 7;

class Solution {
public:
    int countOrders(int n) {
        long long res = 1;
        for(int i = 1; i <= n; ++i){
             res = res * i % MOD;
             res = res * (2 * i - 1) % MOD;
        }
        return res;
    }
};
const MOD = 1e9 + 7;

function countOrders(n) {
  let result = 1;
  for (let i = 1; i <= n; ++i) {
    result = result * i % MOD;
    result = result * (2 * i - 1) % MOD;
  }
  return result;
}

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.

Complexity

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.

Try this approach in the editor

Approach 3: Dynamic Programming

We define f[i] as the number of all valid pickup/delivery sequences for i orders. Initially, f[1] = 1.

We can choose any of these i orders as the last delivery order D_i, then its pickup order P_i can be at any position in the previous 2 times i - 1, and the number of pickup/delivery sequences for the remaining i - 1 orders is f[i - 1], so f[i] can be expressed as:

$ f[i] = i times (2 times i - 1) times f[i - 1]

The final answer is f[n].

We notice that the value of f[i] is only related to f[i - 1], so we can use a variable instead of an array to reduce the space complexity.

The time complexity is O(n), where n is the number of orders. The space complexity is O(1)$.

func countOrders(n int) int {
	const mod = 1e9 + 7
	f := 1
	for i := 2; i <= n; i++ {
		f = f * i * (2*i - 1) % mod
	}
	return f
}
const MOD: i64 = (1e9 as i64) + 7;

impl Solution {
    #[allow(dead_code)]
    pub fn count_orders(n: i32) -> i32 {
        let mut f = 1;
        for i in 2..=n as i64 {
            f = (i * (2 * i - 1) * f) % MOD;
        }
        f as i32
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Recursive Approach with Memoization

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.

Iterative Approach with Combinatorics

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.

Dynamic Programming–

Complexity analysis

ApproachTimeSpaceWhen to Use
Recursive DP with MemoizationO(n^2)O(n^2)When explaining the state transitions or deriving the counting logic step‑by‑step
Iterative Combinatorics FormulaO(n)O(1)Optimal solution for interviews and production due to simple math formula

Frequently asked questions

Is Count All Valid Pickup and Delivery Options easy or hard?

The problem is labeled Hard because deriving the combinatorics formula is not obvious initially. Once the counting pattern is recognized, the final implementation becomes simple and runs in linear time.

Count All Valid Pickup and Delivery Options Python/Java solution

Python and Java implementations typically compute the recurrence f(i) = f(i-1) * i * (2i - 1) using a loop from 1 to n while applying modulo 1e9+7. The code uses integer arithmetic and a single accumulator variable, making the implementation concise and efficient.

How to solve Count All Valid Pickup and Delivery Options in O(n)?

Observe that when adding the i-th order, there are i possible positions for the pickup and (2i−1) valid positions for its delivery relative to other events. Multiply the previous result by i * (2i − 1) for each i from 1 to n. Apply modulo 1e9+7 after every multiplication.

What is the best approach for Count All Valid Pickup and Delivery Options?

The optimal approach uses a combinatorics formula derived from counting valid insertion positions for each new order. The recurrence is f(i) = f(i-1) * i * (2i - 1). Iterating from 1 to n computes the result in O(n) time and O(1) space with modulo 1e9+7.

Is Count All Valid Pickup and Delivery Options asked at Google/Amazon/Meta?

Combinatorics and dynamic programming counting problems like this appear in interviews at companies such as Amazon, Google, and Meta. Interviewers use them to test mathematical reasoning, recurrence derivation, and the ability to optimize DP into a formula.

What data structure is used in Count All Valid Pickup and Delivery Options?

The recursive approach uses memoization with a 2D DP table keyed by remaining pickups and deliveries. The optimal solution does not require a data structure; it relies on combinatorial counting and a running product with modular arithmetic.

What is the time complexity of Count All Valid Pickup and Delivery Options?

The optimal combinatorics solution runs in O(n) time and O(1) space because it only multiplies a running product for each order. A recursive dynamic programming formulation with memoization typically requires O(n^2) time and space due to the number of pickup/delivery states.

Comments

Now write it yourselfClose this page and solve Count All Valid Pickup and Delivery Options in the editor, without looking.
Practise Count All Valid Pickup and Delivery Options