Simulate a Price-Level Tracker for Buy and Sell Orders
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests your ability to combine a hash map with a lazy-deletion heap to track best bid and ask prices across a sequence of order book operations.
Problem
You are building the core of a single-instrument trade ledger. The ledger holds open orders on two sides — buyers and sellers — and must answer price queries at any time.
Each order carries four attributes:
order_id— a unique string identifierside— either"BUY"or"SELL"price— a positive number (float)quantity— a positive integer
You will receive a sequence of operation names paired with their argument lists. Process every operation in order and collect the return value of each one into a result list.
Operations
add_order(order_id, side, price, quantity)
Records a new order. Multiple orders may rest at the same price. Returns None.
cancel_order(order_id)
Removes the order with the given order_id from the ledger. If no such order exists, do nothing. Returns None.
get_best_bid()
Returns the highest price among all live "BUY" orders, or None if no buy orders are present. Arguments list is empty for this operation.
get_best_ask()
Returns the lowest price among all live "SELL" orders, or None if no sell orders are present. Arguments list is empty for this operation.
Input format
operations: List[str] — operation names in call order
arguments: List[List] — parallel list of argument lists
Return a list of the same length as operations. Each element is the return value of the corresponding call.
Constraints
1 <= len(operations) <= 10^4- Every
order_idpassed toadd_orderis unique across all calls. cancel_ordermay be called with anorder_idthat was never added; treat this as a no-op.get_best_bidandget_best_askare called with an empty argument list.priceis a positive float;quantityis a positive integer.- Operations are limited to the four names above.
Examples
Example 1
Input: simulate_order_ledger(['add_order', 'add_order', 'add_order', 'get_best_bid', 'get_best_ask', 'cancel_order', 'get_best_bid'], [['1', 'BUY', 100, 10], ['2', 'BUY', 101, 5], ['3', 'SELL', 105, 20], [], [], ['2'], []])
Output: [None, None, None, 101, 105, None, 100]
Example 2
Input: simulate_order_ledger(['get_best_bid', 'get_best_ask', 'cancel_order'], [[], [], ['missing']])
Output: [None, None, None]
Hints
Hint 1
You need O(1) lookup by order_id for cancellations and O(1) access to the extreme price on each side — no single structure gives you both. Think about pairing a dict with a heap.
Hint 2
A min-heap gives you the lowest price instantly. For the highest buy price, store prices negated so the same min-heap machinery finds the maximum.
Hint 3
When a cancellation empties a price level, you don't have to fix the heap right away. Instead, keep a counter of how many live orders sit at each price and skip over any heap entry whose counter has dropped to zero when you query — this is lazy deletion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two responsibilities, two structures
Every operation falls into one of two categories:
- Mutate by
order_id—add_orderandcancel_orderneed to find or store an order in constant time. - Query the extreme price on a side —
get_best_bidandget_best_askneed the maximum buy price or minimum sell price.
A plain dict handles responsibility 1 in O(1). A heap handles responsibility 2 in O(log P) for updates and O(1) for reads, where P is the number of distinct price levels.
Why lazy deletion works
When cancel_order removes the last order at a given price, the heap still holds that price. Cleaning the heap eagerly would cost O(P) in the worst case. Instead, keep a per-side counter: counts[price] = number of live orders at that price. When it falls to zero, drop the entry from counts but leave the heap alone.
On the next get_best_bid or get_best_ask call, pop heap entries one by one until the front element's price is still in counts (i.e. has a live order). Each stale entry is popped at most once across all future queries, so the total work across the whole operation sequence is O(P log P) — the lazy pops are amortized.
Handling BUY vs SELL direction
Python's heapq is a min-heap. The lowest ask is already at the heap root. For bids we want the highest price, so we push the negation: pushing -price means the most negative value (the largest original price) sits at the root, and we negate it again on read.
The sign parameter in purge_stale encodes this: sign = -1 for BUY (heap stores -price, so sign * heap[0] recovers the real price) and sign = 1 for SELL.
Correctness
- Every live order appears in exactly one entry in
ordersand contributes 1 tocounts[side][price]. - A price exists in
countsonly while at least one live order rests there. - Every live price level has been pushed to the heap at least once (when its first order was added).
- After
purge_stale, the heap root is the first price still present incounts, which is the true best price.
Edge cases
cancel_orderwith an unknown id:orders.pop(order_id, None)returnsNoneand the function does nothing.get_best_bid/get_best_askon an empty side: after purging, the heap is empty, soNoneis returned.- Multiple orders at the same price:
counts[price]tracks all of them; the price stays incountsuntil all are cancelled.
Complexity
| Operation | Time |
|---|---|
add_order | O(log P) when a new price level is created; O(1) otherwise |
cancel_order | O(1) |
get_best_bid / get_best_ask | O(1) amortized (each stale heap entry is popped once, O(log P) per pop) |
Space: O(N + H), where N is the number of live orders and H is the total number of distinct price levels ever created. In the worst case H = N.
Reference solution
import heapq
from typing import List, Optional
def simulate_order_ledger(operations: List[str], arguments: List[List]) -> List[Optional[float]]:
# order_id -> (side, price, quantity)
orders = {}
# Heaps for each side.
# BUY heap stores negated prices so heap[0] is the highest bid.
# SELL heap stores prices directly so heap[0] is the lowest ask.
bid_heap = []
ask_heap = []
# Number of live orders at each price level, per side.
# A price is "alive" iff its count is > 0.
bid_counts = {}
ask_counts = {}
results = []
def purge_stale(heap, counts, sign):
"""Pop heap entries whose price level has no live orders left.
sign = -1 for BUY (prices stored negated), +1 for SELL."""
while heap and counts.get(sign * heap[0], 0) == 0:
heapq.heappop(heap)
for op, args in zip(operations, arguments):
if op == "add_order":
order_id, side, price, quantity = args
orders[order_id] = (side, price, quantity)
if side == "BUY":
heap, counts, stored = bid_heap, bid_counts, -price
else:
heap, counts, stored = ask_heap, ask_counts, price
# Only push to the heap when creating a brand-new price level;
# existing levels are already represented.
if counts.get(price, 0) == 0:
heapq.heappush(heap, stored)
counts[price] = counts.get(price, 0) + 1
results.append(None)
elif op == "cancel_order":
order_id = args[0]
order = orders.pop(order_id, None)
if order is not None:
side, price, _ = order
counts = bid_counts if side == "BUY" else ask_counts
counts[price] -= 1
if counts[price] == 0:
del counts[price] # heap entry cleaned lazily on next query
results.append(None)
elif op == "get_best_bid":
purge_stale(bid_heap, bid_counts, -1)
results.append(-bid_heap[0] if bid_heap else None)
elif op == "get_best_ask":
purge_stale(ask_heap, ask_counts, 1)
results.append(ask_heap[0] if ask_heap else None)
else:
raise ValueError(f"Unknown operation: {op}")
return results