Number of Orders in the Backlog solution and explanation
6 more videos on this problem
LeetCode 1801. Number of Orders in the Backlog | 🏆 Weekly Contest 233 | Medium | Algorithm ExplainedCherry Coding [IIT-G] · 14:01 · 1K views
1801. Number of Orders in the Backlog (Leetcode Medium)Programming Live with Larry · 12:25 · 942 views
【每日一题】1801. Number of Orders in the Backlog, 6/7/2021Huifeng Guan · 18:43 · 430 views
1801. Number of Orders in the BacklogGaurav Codes · 11:41 · 365 views
Leetcode 1801. Number of Orders in the Backlog (2 heaps)LetsCode · 38:44 · 177 views
无讲解 Leetcode 1801 Number of Orders in the Backlog带老婆转码 · 16:39 · 39 views
LeetCode 1801: Number of Orders in the BacklogAlitaCode · 34:18 · 9 views
The problem
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:
0if it is a batch ofbuyorders, or1if it is a batch ofsellorders.
Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
- If the order is a
buyorder, you look at thesellorder with the smallest price in the backlog. If thatsellorder's price is smaller than or equal to the currentbuyorder's price, they will match and be executed, and thatsellorder will be removed from the backlog. Else, thebuyorder is added to the backlog. - Vice versa, if the order is a
sellorder, you look at thebuyorder with the largest price in the backlog. If thatbuyorder's price is larger than or equal to the currentsellorder's price, they will match and be executed, and thatbuyorder will be removed from the backlog. Else, thesellorder is added to the backlog.
Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.
Example 1:
Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]] Output: 6 Explanation: Here is what happens with the orders: - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
Example 2:
Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]] Output: 999999984 Explanation: Here is what happens with the orders: - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).
Constraints:
1 <= orders.length <= 105orders[i].length == 31 <= pricei, amounti <= 109orderTypeiis either0or1.
Approach overview
Problem Overview: You receive a stream of buy and sell orders for a stock. Each order has a price, amount, and type (buy or sell). When possible, orders should match with existing opposite orders in the backlog. After processing all orders, return the total remaining amount in the backlog modulo 1e9 + 7.
Approach 1: Using Two Priority Queues (O(n log n) time, O(n) space)
This approach simulates a real trading order book using two heaps. Maintain a max‑heap for buy orders (highest price first) and a min‑heap for sell orders (lowest price first). When a new buy order arrives, repeatedly match it with the cheapest sell order while the sell price is less than or equal to the buy price. Similarly, when a sell order arrives, match it with the highest buy order while the buy price is greater than or equal to the sell price. Each match reduces quantities until one order is exhausted. Remaining quantities are pushed back into the appropriate heap. Heap operations like push and pop take O(log n), so processing all orders costs O(n log n). This approach directly models the trading system and is the standard solution using a heap (priority queue).
Approach 2: Sorting and Two Pointers (O(n log n) time, O(n) space)
Another way to reason about the problem is to process orders after grouping and sorting them by price. Buy orders are sorted descending by price while sell orders are sorted ascending. Two pointers then iterate through both lists and simulate matching between the current highest buy and lowest sell order. Whenever the buy price is at least the sell price, reduce the smaller amount and move the pointer when an order is exhausted. If prices no longer match, the unmatched orders remain in the backlog. Sorting dominates the runtime at O(n log n), while pointer traversal is linear. This approach avoids heaps but requires preprocessing and additional arrays, making it less natural for streaming input. It still relies on understanding the matching process using arrays and careful simulation of order execution.
Recommended for interviews: The two‑priority‑queue approach is what interviewers expect. It mirrors how real order books work and demonstrates strong knowledge of heaps and simulation problems. The sorting method shows the matching logic clearly but is less flexible because the input is processed sequentially. Showing awareness of both approaches is useful, but implementing the heap-based solution signals solid problem‑solving skill.
Approach 1: Using Two Priority Queues
This approach involves using two priority queues (heaps) to represent the buy and sell orders in the backlog:
- The buy orders are stored in a max-heap based on their price, allowing us to quickly access the order with the highest price.
- The sell orders are stored in a min-heap based on their price, allowing us to quickly access the order with the lowest price.
- For each incoming order, we try to match it with the existing orders in the opposite type's heap. If it can be matched, we reduce the amount accordingly. Otherwise, we add it to the appropriate heap.
from heapq import heappush, heappop
def process_orders(orders):
MOD = 10**9 + 7
buy_heap = [] # Max-heap for buy orders
sell_heap = [] # Min-heap for sell orders
for price, amount, order_type in orders:
if order_type == 0: # Buy order
while sell_heap and amount > 0 and sell_heap[0][0] <= price:
sell_price, sell_amount = heappop(sell_heap)
if sell_amount > amount:
sell_amount -= amount
heappush(sell_heap, (sell_price, sell_amount))
amount = 0
else:
amount -= sell_amount
if amount > 0:
heappush(buy_heap, (-price, amount))
else: # Sell order
while buy_heap and amount > 0 and -buy_heap[0][0] >= price:
buy_price, buy_amount = heappop(buy_heap)
if buy_amount > amount:
buy_amount -= amount
heappush(buy_heap, (buy_price, buy_amount))
amount = 0
else:
amount -= buy_amount
if amount > 0:
heappush(sell_heap, (price, amount))
total_orders = sum(a for _, a in buy_heap) + sum(a for _, a in sell_heap)
return total_orders % MOD
# Example usage
orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
print(process_orders(orders)) # Output: 6import java.util.*;
class Solution {
public int processOrders(int[][] orders) {
long MOD = 1000000007;
PriorityQueue<int[]> buyHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
PriorityQueue<int[]> sellHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int[] order : orders) {
int price = order[0], amount = order[1], type = order[2];
if (type == 0) { // Buy
while (amount > 0 && !sellHeap.isEmpty() && sellHeap.peek()[0] <= price) {
int[] sellOrder = sellHeap.poll();
int sellAmount = Math.min(amount, sellOrder[1]);
amount -= sellAmount;
sellOrder[1] -= sellAmount;
if (sellOrder[1] > 0) sellHeap.add(sellOrder);
}
if (amount > 0) buyHeap.add(new int[]{price, amount});
} else { // Sell
while (amount > 0 && !buyHeap.isEmpty() && buyHeap.peek()[0] >= price) {
int[] buyOrder = buyHeap.poll();
int buyAmount = Math.min(amount, buyOrder[1]);
amount -= buyAmount;
buyOrder[1] -= buyAmount;
if (buyOrder[1] > 0) buyHeap.add(buyOrder);
}
if (amount > 0) sellHeap.add(new int[]{price, amount});
}
}
long totalOrders = 0;
for (int[] order : buyHeap) totalOrders = (totalOrders + order[1]) % MOD;
for (int[] order : sellHeap) totalOrders = (totalOrders + order[1]) % MOD;
return (int) totalOrders;
}
// Example usage
// public static void main(String[] args) {
// Solution sol = new Solution();
// int[][] orders = {{10,5,0},{15,2,1},{25,1,1},{30,4,0}};
// System.out.println(sol.processOrders(orders)); // Output: 6
// }
}#include <vector>
#include <queue>
#include <functional>
using namespace std;
int processOrders(vector<vector<int>>& orders) {
long MOD = 1000000007;
priority_queue<pair<int, int>> buyHeap;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> sellHeap;
for (auto& order : orders) {
int price = order[0], amount = order[1], type = order[2];
if (type == 0) {
while (amount > 0 && !sellHeap.empty() && sellHeap.top().first <= price) {
auto [sellPrice, sellAmount] = sellHeap.top();
sellHeap.pop();
if (sellAmount > amount) {
sellHeap.emplace(sellPrice, sellAmount - amount);
amount = 0;
} else {
amount -= sellAmount;
}
}
if (amount > 0) buyHeap.emplace(price, amount);
} else {
while (amount > 0 && !buyHeap.empty() && buyHeap.top().first >= price) {
auto [buyPrice, buyAmount] = buyHeap.top();
buyHeap.pop();
if (buyAmount > amount) {
buyHeap.emplace(buyPrice, buyAmount - amount);
amount = 0;
} else {
amount -= buyAmount;
}
}
if (amount > 0) sellHeap.emplace(price, amount);
}
}
long totalOrders = 0;
while (!buyHeap.empty()) {
totalOrders = (totalOrders + buyHeap.top().second) % MOD;
buyHeap.pop();
}
while (!sellHeap.empty()) {
totalOrders = (totalOrders + sellHeap.top().second) % MOD;
sellHeap.pop();
}
return totalOrders;
}
// Example usage
// int main() {
// vector<vector<int>> orders = {{10,5,0},{15,2,1},{25,1,1},{30,4,0}};
// cout << processOrders(orders) << endl; // Output: 6
// }function getNumberOfBacklogOrders(orders) {
const MOD = 1000000007;
const buyHeap = new MinPriorityQueue({ priority: x => -x[0] });
const sellHeap = new MinPriorityQueue({ priority: x => x[0] });
for (const [price, amount, orderType] of orders) {
if (orderType === 0) { // Buy
let _amount = amount;
while (_amount > 0 && !sellHeap.isEmpty() && sellHeap.front().element[0] <= price) {
let [sellPrice, sellAmount] = sellHeap.dequeue().element;
const minAmount = Math.min(_amount, sellAmount);
_amount -= minAmount;
sellAmount -= minAmount;
if (sellAmount > 0) sellHeap.enqueue([sellPrice, sellAmount]);
}
if (_amount > 0) buyHeap.enqueue([price, _amount]);
} else { // Sell
let _amount = amount;
while (_amount > 0 && !buyHeap.isEmpty() && buyHeap.front().element[0] >= price) {
let [buyPrice, buyAmount] = buyHeap.dequeue().element;
const minAmount = Math.min(_amount, buyAmount);
_amount -= minAmount;
buyAmount -= minAmount;
if (buyAmount > 0) buyHeap.enqueue([buyPrice, buyAmount]);
}
if (_amount > 0) sellHeap.enqueue([price, _amount]);
}
}
let totalOrders = 0;
while (!buyHeap.isEmpty()) totalOrders = (totalOrders + buyHeap.dequeue().element[1]) % MOD;
while (!sellHeap.isEmpty()) totalOrders = (totalOrders + sellHeap.dequeue().element[1]) % MOD;
return totalOrders;
}
// Example usage
// const orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]];
// console.log(getNumberOfBacklogOrders(orders)); // Output: 6using System;
using System.Collections.Generic;
public class Solution {
public int GetNumberOfBacklogOrders(int[][] orders) {
long MOD = 1000000007;
PriorityQueue<int[], int> buyQueue = new PriorityQueue<int[], int>(Comparer<int>.Create((a, b) => b - a));
PriorityQueue<int[], int> sellQueue = new PriorityQueue<int[], int>();
foreach (var order in orders) {
int price = order[0], amount = order[1], type = order[2];
if (type == 0) { // Buy
while (amount > 0 && sellQueue.Count > 0 && sellQueue.Peek()[0] <= price) {
var sellOrder = sellQueue.Dequeue();
int minAmount = Math.Min(amount, sellOrder[1]);
amount -= minAmount;
sellOrder[1] -= minAmount;
if (sellOrder[1] > 0) sellQueue.Enqueue(sellOrder, sellOrder[0]);
}
if (amount > 0) buyQueue.Enqueue(new int[] { price, amount }, price);
} else { // Sell
while (amount > 0 && buyQueue.Count > 0 && buyQueue.Peek()[0] >= price) {
var buyOrder = buyQueue.Dequeue();
int minAmount = Math.Min(amount, buyOrder[1]);
amount -= minAmount;
buyOrder[1] -= minAmount;
if (buyOrder[1] > 0) buyQueue.Enqueue(buyOrder, buyOrder[0]);
}
if (amount > 0) sellQueue.Enqueue(new int[] { price, amount }, price);
}
}
long totalOrders = 0;
while (buyQueue.Count > 0) totalOrders = (totalOrders + buyQueue.Dequeue()[1]) % MOD;
while (sellQueue.Count > 0) totalOrders = (totalOrders + sellQueue.Dequeue()[1]) % MOD;
return (int)totalOrders;
}
// Example usage
// public static void Main() {
// Solution sol = new Solution();
// int[][] orders = { new int[] { 10, 5, 0 }, new int[] { 15, 2, 1 },
// new int[] { 25, 1, 1 }, new int[] { 30, 4, 0 } };
// Console.WriteLine(sol.GetNumberOfBacklogOrders(orders)); // Output: 6
// }
}This Python solution uses two heaps to manage the buy and sell orders:
- The buy orders are stored in a max-heap (using negative prices to simulate max behavior).
- The sell orders are stored in a min-heap.
- Every order is processed by attempting to match it with opposite orders in the backlog. If they are matchable, execution occurs reducing the order amount on both ends. Orders that can't be completely matched are added to their respective heaps.
Time Complexity: O(n log n), where n is the number of orders since each order insertion/deletion into the heap takes O(log n), and there can be at most n such operations.
Space Complexity: O(n), storing all unmatched orders in heaps.
Approach 2: Using Sorting and Two Pointers
This approach leverages sorting to handle and manage orders efficiently:
- First, separate the orders into buy and sell lists.
- Sort buy orders in descending order by price and sell orders in ascending order by price.
- Use two pointers to traverse the buy and sell lists to match orders. Execute matching as long as the buy price is greater than or equal to the sell price.
- When matching isn’t possible, simply track unmatched orders in a combined list.
This approach can be efficient, as sorting can be done in O(n log n), allowing a straightforward linear scan for matching orders.
def process_orders_sorting(orders):
MOD = 10**9 + 7
buy_orders = []
sell_orders = []
for price, amount, type_ in orders:
if type_ == 0:
buy_orders.append((price, amount))
else:
sell_orders.append((price, amount))
buy_orders.sort(key=lambda x: -x[0])
sell_orders.sort(key=lambda x: x[0])
i, j = 0, 0
while i < len(buy_orders) and j < len(sell_orders):
buy_price, buy_amount = buy_orders[i]
sell_price, sell_amount = sell_orders[j]
if buy_price >= sell_price:
matched_amount = min(buy_amount, sell_amount)
buy_orders[i] = (buy_price, buy_amount - matched_amount)
sell_orders[j] = (sell_price, sell_amount - matched_amount)
if buy_amount - matched_amount == 0:
i += 1
if sell_amount - matched_amount == 0:
j += 1
else:
break
total_backlog = sum(a for _, a in buy_orders) + sum(a for _, a in sell_orders)
return total_backlog % MOD
# Example usage
orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
print(process_orders_sorting(orders)) # Output: 6function getNumberOfBacklogOrdersWithSorting(orders) {
const MOD = 1000000007;
const buyOrders = [];
const sellOrders = [];
for (const [price, amount, type] of orders) {
if (type === 0) {
buyOrders.push([price, amount]);
} else {
sellOrders.push([price, amount]);
}
}
buyOrders.sort((a, b) => b[0] - a[0]);
sellOrders.sort((a, b) => a[0] - b[0]);
let i = 0, j = 0;
while (i < buyOrders.length && j < sellOrders.length) {
const [buyPrice, buyAmount] = buyOrders[i];
const [sellPrice, sellAmount] = sellOrders[j];
if (buyPrice >= sellPrice) {
const matchAmount = Math.min(buyAmount, sellAmount);
buyOrders[i][1] -= matchAmount;
sellOrders[j][1] -= matchAmount;
if (buyOrders[i][1] === 0) i++;
if (sellOrders[j][1] === 0) j++;
} else {
break;
}
}
let totalBacklog = 0;
for (const [_, amount] of buyOrders) totalBacklog = (totalBacklog + amount) % MOD;
for (const [_, amount] of sellOrders) totalBacklog = (totalBacklog + amount) % MOD;
return totalBacklog;
}
// Example usage
// const orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]];
// console.log(getNumberOfBacklogOrdersWithSorting(orders)); // Output: 6This solution involves sorting both buy and sell orders to efficiently match them using two pointers:
- Buy orders are sorted in descending order, while sell orders are in ascending order.
- Using a two-pointer technique, orders are matched if possible and reduced accordingly.
- Unmatched orders are simply accumulated in their respective lists to count total backlog.
Time Complexity: O(n log n) due to sorting, followed by O(n) scanning.
Space Complexity: O(n) to store orders separately.
Approach 3: Priority Queue (Max-Min Heap) + Simulation
We can use a priority queue (max-min heap) to maintain the current backlog of orders, where the max heap buy maintains the backlog of purchase orders, and the min heap sell maintains the backlog of sales orders. Each element in the heap is a tuple (price, amount), indicating that the number of orders at price price is amount.
Next, we traverse the order array orders, and simulate according to the problem's requirements.
After the traversal, we add the order quantities in buy and sell, which is the final backlog of orders. Note that the answer may be very large, so we need to take the modulus of 10^9 + 7.
The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of orders.
func getNumberOfBacklogOrders(orders [][]int) (ans int) {
sell := hp{}
buy := hp{}
for _, e := range orders {
p, a, t := e[0], e[1], e[2]
if t == 0 {
for a > 0 && len(sell) > 0 && sell[0].p <= p {
q := heap.Pop(&sell).(pair)
x, y := q.p, q.a
if a >= y {
a -= y
} else {
heap.Push(&sell, pair{x, y - a})
a = 0
}
}
if a > 0 {
heap.Push(&buy, pair{-p, a})
}
} else {
for a > 0 && len(buy) > 0 && -buy[0].p >= p {
q := heap.Pop(&buy).(pair)
x, y := q.p, q.a
if a >= y {
a -= y
} else {
heap.Push(&buy, pair{x, y - a})
a = 0
}
}
if a > 0 {
heap.Push(&sell, pair{p, a})
}
}
}
const mod int = 1e9 + 7
for len(buy) > 0 {
ans += heap.Pop(&buy).(pair).a
}
for len(sell) > 0 {
ans += heap.Pop(&sell).(pair).a
}
return ans % mod
}
type pair struct{ p, a int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].p < h[j].p }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }Complexity comparison
| Approach | Complexity |
|---|---|
| Using Two Priority Queues | Time Complexity: O(n log n), where n is the number of orders since each order insertion/deletion into the heap takes O(log n), and there can be at most n such operations. |
| Using Sorting and Two Pointers | Time Complexity: O(n log n) due to sorting, followed by O(n) scanning. |
| Priority Queue (Max-Min Heap) + Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two Priority Queues (Order Book Simulation) | O(n log n) | O(n) | General case. Best for streaming order processing and typical interview expectations. |
| Sorting + Two Pointers | O(n log n) | O(n) | Useful when orders can be preprocessed and sorted before matching. |
Frequently asked questions
Is Number of Orders in the Backlog easy or hard?
The problem is rated Medium because it combines multiple concepts: heaps, greedy matching, and simulation. The logic itself is straightforward once the order-book model is understood, but careful handling of quantities and heap operations is required.
How to solve Number of Orders in the Backlog efficiently?
Use two heaps to simulate an order book. Store buy orders in a max-heap and sell orders in a min-heap. For every incoming order, repeatedly match it with the best available opposite order while prices satisfy the matching condition. Update quantities and push remaining amounts back into the heap.
What is the best approach for Number of Orders in the Backlog?
The best approach uses two priority queues: a max-heap for buy orders and a min-heap for sell orders. This structure always exposes the highest buy price and lowest sell price so matching can happen immediately. Each insertion or removal from the heap costs O(log n), giving an overall complexity of O(n log n) for processing all orders.
What data structure is used in Number of Orders in the Backlog?
The key data structure is a priority queue (heap). A max-heap tracks the highest buy price, while a min-heap tracks the lowest sell price. These structures make it efficient to find the next valid order to match.
What is the time complexity of Number of Orders in the Backlog?
The optimal solution runs in O(n log n) time. Each order may be inserted into or removed from a heap, and heap operations take O(log n). Space complexity is O(n) because unmatched orders remain stored in the buy and sell priority queues.
Is Number of Orders in the Backlog asked at Google, Amazon, or Meta?
Problems involving heaps and order-book style simulations frequently appear in interviews at companies like Amazon, Google, and trading-related firms. The question tests priority queues, greedy matching logic, and careful simulation of state changes.
Is there a Python or Java solution for Number of Orders in the Backlog?
Most implementations use built-in heap libraries. Python uses heapq with negative values to simulate a max-heap for buy orders, while Java uses PriorityQueue with custom comparators. The algorithm remains the same across Python, Java, C++, C#, and JavaScript.
