#1801
Number of Orders in the Backlog
MediumArrayHeap (Priority Queue)SimulationHeap (Priority Queue)Simulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
In the optimal approach, we use two heaps (priority queues) to efficiently manage buy and sell orders. This allows us to quickly match orders without needing to iterate through the entire backlog.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a max heap for buy orders and a min heap for sell orders.
- 2Step 2: For each order, process it based on its type, matching it with the appropriate orders from the heaps.
- 3Step 3: If an order cannot be matched, add it to the respective heap.
- 4Step 4: At the end, sum the amounts in both heaps to get the total backlog.
solution.py29 lines
1# Full working Python code
2import heapq
3class Solution:
4 def getNumberOfBacklogOrders(self, orders):
5 buy_orders = [] # max heap
6 sell_orders = [] # min heap
7 for price, amount, orderType in orders:
8 if orderType == 0: # Buy order
9 while amount > 0 and sell_orders and sell_orders[0][0] <= price:
10 sell_price, sell_amount = heapq.heappop(sell_orders)
11 if sell_amount <= amount:
12 amount -= sell_amount
13 else:
14 heapq.heappush(sell_orders, (sell_price, sell_amount - amount))
15 amount = 0
16 if amount > 0:
17 heapq.heappush(buy_orders, (-price, amount)) # store as negative for max heap
18 else: # Sell order
19 while amount > 0 and buy_orders and -buy_orders[0][0] >= price:
20 buy_price, buy_amount = heapq.heappop(buy_orders)
21 if buy_amount <= amount:
22 amount -= buy_amount
23 else:
24 heapq.heappush(buy_orders, (buy_price, buy_amount - amount))
25 amount = 0
26 if amount > 0:
27 heapq.heappush(sell_orders, (price, amount))
28 total = sum(amount for _, amount in buy_orders) + sum(amount for _, amount in sell_orders)
29 return total % (10**9 + 7)ℹ
Complexity note: The time complexity is O(n log n) due to the heap operations (insert and remove) being logarithmic in nature, while we process each order once.
- 1Using heaps allows for efficient order matching, reducing the time complexity significantly.
- 2Understanding the nature of buy and sell orders helps in structuring the heaps correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.