Number of Orders in the Backlog - Problem
๐ Stock Market Order Matching System
You're building a stock trading order matching engine! Given a sequence of buy and sell orders, you need to simulate how they would be matched and executed.
Each order is represented as [price, amount, orderType] where:
- orderType = 0: Buy order (wants to purchase stock)
- orderType = 1: Sell order (wants to sell stock)
๐ Matching Rules:
- Buy Order: Matches with the cheapest sell order if sell price โค buy price
- Sell Order: Matches with the highest buy order if buy price โฅ sell price
- Unmatched orders go into a backlog (pending orders)
Return the total number of orders remaining in the backlog after processing all orders. Since the result can be large, return it modulo 109 + 7.
๐ก Think of it like a marketplace where buyers want low prices and sellers want high prices - orders only execute when both parties agree!
Input & Output
example_1.py โ Basic Order Matching
$
Input:
orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
โบ
Output:
6
๐ก Note:
Buy order [10,5,0] โ backlog: buy[(10,5)]. Sell order [15,2,1] โ no match, backlog: buy[(10,5)], sell[(15,2)]. Sell order [25,1,1] โ no match, backlog: buy[(10,5)], sell[(15,2), (25,1)]. Buy order [30,4,0] โ matches sell (15,2) and sell (25,1), uses 3 orders, 1 remaining โ backlog: buy[(10,5), (30,1)]. Total: 5+1 = 6
example_2.py โ Complete Matching
$
Input:
orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
โบ
Output:
999999984
๐ก Note:
Large sell order gets partially matched by smaller buy orders. The remaining amount is (1000000000 - 3 - 1) % (10^9 + 7) = 999999996. But after all matching, total backlog is 999999984.
example_3.py โ No Matches
$
Input:
orders = [[1,2,0],[2,3,0],[10,1,1]]
โบ
Output:
6
๐ก Note:
Buy orders at $1 and $2, sell order at $10. No matches since sell price > buy prices. All orders go to backlog: 2+3+1 = 6
Visualization
Tap to expand
Understanding the Visualization
1
Order Arrival
New buy/sell order arrives at the exchange
2
Priority Check
Check top of relevant heap for best matching candidate
3
Match & Execute
If prices are compatible, execute the trade
4
Update Backlog
Add unmatched portion to appropriate priority queue
Key Takeaway
๐ฏ Key Insight: Priority queues transform O(nยฒ) brute force matching into O(n log n) by maintaining sorted order automatically, making real-time trading feasible!
Time & Space Complexity
Time Complexity
O(n log n)
Each order involves O(log n) heap operations, and we process n orders
โก Linearithmic
Space Complexity
O(n)
Store up to n orders in the two priority queues
โก Linearithmic Space
Constraints
- 1 โค orders.length โค 105
- orders[i].length == 3
- 1 โค pricei, amounti โค 109
- orderTypei is either 0 or 1
- Large amounts require modulo arithmetic
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code