Number of Orders in the Backlog - 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 of buy orders, or1if it is a batch of sell orders.
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 buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
- Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order 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 10^9 + 7.
Input & Output
Example 1 — Basic Matching
$
Input:
orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
›
Output:
6
💡 Note:
Buy 10 (5 units) matches with sell 15 (2 units), leaving buy 10 (3 units). Sell 25 (1 unit) matches with buy 30 (4 units), leaving buy 30 (3 units). Total backlog: 3 + 3 = 6
Example 2 — No Matches
$
Input:
orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
›
Output:
999999984
💡 Note:
Sell 7 can't match with any buy order, buy orders can't match with remaining sell. Only some units of large sell order get matched.
Example 3 — Complete Match
$
Input:
orders = [[10,2,0],[8,3,1]]
›
Output:
1
💡 Note:
Buy 10 (2 units) matches with sell 8 (3 units) since 8 ≤ 10. 2 units matched, leaving sell 8 (1 unit) in backlog.
Constraints
- 1 ≤ orders.length ≤ 105
- orders[i].length == 3
- 1 ≤ pricei, amounti ≤ 109
- orderTypei is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Orders
Process buy/sell orders with price, amount, and type
2
Match Orders
Buy orders match with sell orders at compatible prices
3
Count Backlog
Sum all unmatched orders remaining in the system
Key Takeaway
🎯 Key Insight: Use max-heap for buy orders and min-heap for sell orders to instantly access the best matching prices
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code