Multi-Venue Order Book for BBO and NBBO
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build an in-memory multi-venue limit order book that tracks aggregated resting volume across several trading venues and answers both single-venue top-of-book queries and consolidated market-wide top-of-book queries.
Implement the runner function:
def run_order_book(operations: List[str], arguments: List[List]) -> List[List[Optional[float]]]:
operations and arguments are parallel lists of equal length executed sequentially against one initially empty order book. Each step runs one of three commands and appends its result to the output list:
"add"with[exchange, price, quantity, side]:exchange(str): identifier of the trading venue.price(intorfloat): price level on that venue.quantity(intorfloat): signed volume change applied to(exchange, side, price). Positive values add resting volume; negative values cancel or fill existing volume;0leaves the level unchanged.side(str): either"bid"(buy side, where higher prices rank better) or"ask"(sell side, where lower prices rank better).- Volume is tracked solely in aggregate per
(exchange, side, price)without individual order IDs. A price level is active only while its total volume is strictly greater than0. Whenever an update brings a level's total volume to0or below, that level is removed completely (never stored as a negative balance, so a later positive"add"starts fresh from0). - Appends
Noneto the output list.
"get_exchange_bbo"with[exchange]:- Appends
[best_bid, best_ask]forexchange, wherebest_bidis the highest active"bid"price onexchangeandbest_askis the lowest active"ask"price onexchange. - If a side has no active price levels—or
exchangehas never appeared—returnNonefor that side.
- Appends
"get_nbbo"with[]:- Appends
[national_best_bid, national_best_ask]across all venues combined: the maximum active"bid"price on any venue and the minimum active"ask"price on any venue, usingNonefor any side that has no active volume anywhere. - Venues do not match trades against each other inside this book; if one venue's bid meets or exceeds another venue's ask, report both top prices as stored.
- Appends
Your design should avoid linear scans when deep price levels empty on an exchange and should answer "get_nbbo" without rescanning every resting price level across all venues on each query.
Examples
Example 1
- Input:
operations = ["add", "add", "add", "add", "get_exchange_bbo", "get_exchange_bbo", "get_nbbo"]arguments = [["BATS", 50.0, 20, "bid"], ["BATS", 50.5, 15, "ask"], ["IEX", 50.2, 12, "bid"], ["IEX", 50.8, 10, "ask"], ["BATS"], ["EDGX"], []]
- Output:
[None, None, None, None, [50.0, 50.5], [None, None], [50.2, 50.5]] - Explanation:
"BATS"quotes50.0bid and50.5ask, so its venue BBO is[50.0, 50.5]."EDGX"has no active levels, returning[None, None]. Across"BATS"and"IEX", the highest bid is"IEX"at50.2and the lowest ask is"BATS"at50.5, yielding an NBBO of[50.2, 50.5].
Example 2
- Input:
operations = ["add", "add", "add", "add", "get_nbbo", "add", "get_exchange_bbo", "get_nbbo"]arguments = [["V1", 25, 6, "bid"], ["V1", 24, 9, "bid"], ["V2", 24.5, 5, "bid"], ["V2", 26, 4, "ask"], [], ["V1", 25, -6, "bid"], ["V1"], []]
- Output:
[None, None, None, None, [25, 26], None, [24, None], [24.5, 26]] - Explanation: Before the cancellation,
"V1"holds the highest bid at25and"V2"holds the only ask at26, giving[25, 26]. Applying-6at("V1", "bid", 25)depletes that level to0, so"V1"falls back to its deeper bid24([24, None]), while the cross-venue best bid shifts to"V2"at24.5([24.5, 26]).
Constraints
0 <= len(operations) == len(arguments) <= 100,000sideis always"bid"or"ask"exchangeis a non-empty stringprice > 0(intorfloat);quantityis a signedintorfloat- Aim for
O(log U)amortized time per"add"andO(1)worst-case / amortized time per BBO / NBBO query, whereUis the number of"add"operations
Step-by-step walkthrough
Understand the goal and market rules
In financial markets, a bid is a buyer's offer to buy at a given price (buyers compete by offering higher prices), and an ask (or offer) is a seller's offer to sell at a given price (sellers compete by offering lower prices).
- Per-exchange BBO (Best Bid and Offer):
[highest_bid, lowest_ask]currently active on one specific exchange. - Cross-exchange NBBO (National Best Bid and Offer):
[highest_bid, lowest_ask]across all exchanges combined.
BATS active bids: {50.0: 20} active asks: {50.5: 15} -> BATS BBO = [50.0, 50.5] IEX active bids: {50.2: 12} active asks: {50.8: 10} -> IEX BBO = [50.2, 50.8] ----------------------------------------------------------------------------------- Across all venues: max bid = 50.2 (IEX), min ask = 50.5 (BATS) -> NBBO = [50.2, 50.5]Let's pin down the exact rules for
add(exchange, price, quantity, side): -quantityis a signed change (delta) to the resting quantity at(exchange, side, price)andaddreturnsNone. - A price level is active only while its total quantity is strictly greater than0. If a negativequantitybrings the total to0(or below), the level is removed completely; a later positiveaddstarts fresh from0. - If a side has no active price levels—or an exchange has never been seen—its best price isNone.- Per-exchange BBO (Best Bid and Offer):
Why scanning every price level is too slow
A simple brute-force model stores one dictionary
(exchange, side, price) -> total_qtyand scans every active key on eachget_exchange_bboorget_nbbocall.Updating the dictionary takes
O(1)time, which is great, but every query takesO(L)time whereLis the number of active price levels. Real order books hold thousands of resting price levels deep behind the top of book, and Part 2 explicitly asks us to answerget_nbbo()without rescanning every level.On the flip side, if we kept sorted lists or heaps of prices and tried to immediately delete an arbitrary price from the middle whenever its quantity hit zero, finding and removing that element in a heap or array would still take
O(L)linear search!Part 1: Per-exchange `SideBook` with lazy deletion
We get fast updates and fast top-of-book lookups by splitting quantity tracking from price ordering inside each
(exchange, side):quantitiesdictionary ({price: total_qty}): The single source of truth. Only active prices (total_qty > 0) live in this dictionary.heaplist (a min-heap of price keys): Orders candidate prices. Python'sheapqalways puts the smallest number atheap[0], so ask prices go in directly (price), while bid prices go in negated (-price) so the largest bid sits atheap[0].
When a price level drops to
0, we delete it fromquantitiesinO(1)time and leave its old key sitting insideheap. We only pop stale keys when they actually reachheap[0]insidebest_price(). Deferring cleanup until an item surfaces at the top of a heap is called lazy deletion.SideBook("bid") after adding 100 (+5), 102 (+1), 101 (+3), then cancelling 101 (-3): quantities (truth): {100: 5, 102: 1} <-- 101 removed immediately in O(1) heap (min-heap): [-102, -100, -101] <-- stale -101 stays buried at no cost! If 102 is later cancelled (-1): quantities (truth): {100: 5} best_price() checks heap[0] = -102 -> 102 not in quantities -> pop! Next heap[0] = -100 -> 100 IS in quantities -> return 100!What if a cancelled price (
101) is added back before its old-101entry was popped? Because101is not inquantities, we push-101when reactivating it. Having two-101entries inheapis completely harmless: while101is active both represent the valid price101, and once101empties againbest_price()pops both when they reach the top.import heapq BID = "bid" ASK = "ask" def heap_key(price, side: str): # heapq is a min-heap: negate bids so the highest bid has the smallest key. if side == BID: return -price return price def price_from_key(key, side: str): if side == BID: return -key return key class SideBook: """Tracks one side (bid or ask) of a single exchange.""" def __init__(self, side: str): self.side = side self.quantities = {} # {price: resting_qty > 0} — source of truth self.heap = [] # min-heap of heap_key(price, side); may hold stale keys def add(self, price, delta) -> None: old_qty = self.quantities.get(price, 0) new_qty = old_qty + delta if new_qty > 0: was_inactive = price not in self.quantities self.quantities[price] = new_qty if was_inactive: heapq.heappush(self.heap, heap_key(price, self.side)) elif price in self.quantities: del self.quantities[price] def best_price(self): while self.heap: candidate_price = price_from_key(self.heap[0], self.side) if candidate_price in self.quantities: return candidate_price heapq.heappop(self.heap) return NonePart 2: Cross-exchange NBBO with a global heap of tops
Notice that the global NBBO bid is simply the maximum of each exchange's current best bid. Deeper levels on an exchange cannot affect the NBBO until they become that exchange's own best price!
So we build a second lazy-heap layer on top of the per-exchange books:
Per-Exchange Layer Global Layer ------------------ ------------ BATS SideBook(BID) --best_price()--\ +--> exchange_best[(ex, side)] IEX SideBook(BID) --best_price()--/ | v (push on any change) global_heaps[BID] entries: (-price, exchange)Why must each entry in
global_heaps[side]store both(heap_key(price, side), exchange)rather thanpricealone? Because to check whether a global heap entry is still fresh, we need to ask: "IsexchangeSTILL quotingpriceas its current best on this side?" We verify that inO(1)time by checkingself.exchange_best.get((exchange, side)) == candidate_price.And notice when we update
exchange_bestand push toglobal_heaps: whenevernew_best != old_best—not only when an exchange's best improves, but also when its top level empties and falls back to a worse price (orNone)!from typing import List, Optional class OrderBook: """Aggregates per-exchange order books and maintains cross-exchange NBBO.""" def __init__(self): self.books = {} self.exchange_best = {} self.global_heaps = {BID: [], ASK: []} def add(self, exchange: str, price, quantity, side: str) -> None: if side != BID and side != ASK: raise ValueError(f"side must be 'bid' or 'ask', got {side!r}") if exchange not in self.books: self.books[exchange] = {BID: SideBook(BID), ASK: SideBook(ASK)} side_book = self.books[exchange][side] side_book.add(price, quantity) new_best = side_book.best_price() old_best = self.exchange_best.get((exchange, side)) if new_best != old_best: self.exchange_best[(exchange, side)] = new_best if new_best is not None: heap_entry = (heap_key(new_best, side), exchange) heapq.heappush(self.global_heaps[side], heap_entry) def get_exchange_bbo(self, exchange: str) -> List[Optional[float]]: best_bid = self.exchange_best.get((exchange, BID)) best_ask = self.exchange_best.get((exchange, ASK)) return [best_bid, best_ask] def _global_best_on_side(self, side: str): heap = self.global_heaps[side] while heap: key, exchange = heap[0] candidate_price = price_from_key(key, side) if self.exchange_best.get((exchange, side)) == candidate_price: return candidate_price heapq.heappop(heap) return None def get_nbbo(self) -> List[Optional[float]]: return [self._global_best_on_side(BID), self._global_best_on_side(ASK)]Wire up the operation runner
The judge passes parallel lists
operationsandarguments. Each"add"appendsNoneto the output list, while"get_exchange_bbo"and"get_nbbo"append[best_bid, best_ask].def run_order_book(operations: List[str], arguments: List[List]) -> List[List[Optional[float]]]: book = OrderBook() results: List[Optional[List[Optional[float]]]] = [] for op, args in zip(operations, arguments): if op == "add": book.add(args[0], args[1], args[2], args[3]) results.append(None) elif op == "get_exchange_bbo": results.append(book.get_exchange_bbo(args[0])) elif op == "get_nbbo": results.append(book.get_nbbo()) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 2 step by step
Let's trace Example 2 (
V1posting two bid levels,V2posting a bid and an ask, andV1's top bid depleting):1. add("V1", 25, +6, "bid") -> V1 best bid: None -> 25 global_heaps["bid"]: [(-25, "V1")] 2. add("V1", 24, +9, "bid") -> V1 quantities={25:6, 24:9}, best bid stays 25 (no change to V1's top, so nothing pushed to global_heaps) 3. add("V2", 24.5, +5, "bid") -> V2 best bid: None -> 24.5 global_heaps["bid"]: [(-25, "V1"), (-24.5, "V2")] 4. add("V2", 26, +4, "ask") -> V2 best ask: None -> 26 global_heaps["ask"]: [(26, "V2")] 5. get_nbbo(): - bid top (-25, "V1"): exchange_best[("V1","bid")] == 25 (valid!) -> 25 - ask top (26, "V2"): exchange_best[("V2","ask")] == 26 (valid!) -> 26 Returns [25, 26] 6. add("V1", 25, -6, "bid") -> V1 level 25 empties; SideBook pops -25 and exposes 24! exchange_best[("V1","bid")] updates 25 -> 24, pushing (-24, "V1") to global_heaps["bid"] global_heaps["bid"] now holds [(-25, "V1"), (-24.5, "V2"), (-24, "V1")] 7. get_exchange_bbo("V1") -> O(1) lookup returns [24, None] 8. get_nbbo(): - bid top (-25, "V1") != exchange_best[("V1","bid")] (24) -> stale! pop (-25, "V1") - next bid top (-24.5, "V2") == exchange_best[("V2","bid")] (24.5) -> valid! Returns [24.5, 26]Part 3: Amortized vs. worst-case complexity
Let
Ube the total number ofaddcalls so far andQbe the number of queries: - Everyaddpushes at most 1 entry onto aSideBookheap and at most 1 entry onto aglobal_heapsheap (<= 2Upushes ever, and every heap has size<= U). - Imagine taping one prepaid coin onto every entry at the moment it is pushed (O(log U)work). Whenever awhileloop pops a stale entry later—whether insideaddorget_nbbo—that entry spends its coin to pay for its ownO(log U)heappop, and can never be popped again! - Therefore,Uupdates andQqueries takeO(U log U + Q)total time: -add:O(log U)amortized,O(k log U)worst-case ifkstale entries surface at once. -get_exchange_bbo:O(1)worst-case (two dictionary lookups inexchange_best). -get_nbbo:O(1)amortized,O(k log U)worst-case ifkstale global entries surface at once.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq BID = "bid" ASK = "ask" def heap_key(price, side: str): # heapq is a min-heap (smallest key on top). # Asks want the lowest price first, so keep price as-is; # bids want the highest price first, so negate price to flip the order. if side == BID: return -price return price def price_from_key(key, side: str): # Undo the negation used for bid keys so callers always get real prices. if side == BID: return -key return key class SideBook: """Tracks one side (bid or ask) of a single exchange.""" def __init__(self, side: str): self.side = side # quantities: {price: total_resting_qty} for active levels only (qty > 0). # Example: {100.0: 10, 101.0: 4}. Single source of truth for active prices. self.quantities = {} # heap: min-heap of heap_key(price, side). May still hold stale keys # for levels whose quantity later dropped to 0 (lazy deletion). self.heap = [] def add(self, price, delta) -> None: old_qty = self.quantities.get(price, 0) new_qty = old_qty + delta if new_qty > 0: was_inactive = price not in self.quantities self.quantities[price] = new_qty if was_inactive: # Level just became active: push its key so best_price() can see it. # Any older stale copy buried in self.heap is harmless and gets # popped lazily once this price level empties again. heapq.heappush(self.heap, heap_key(price, self.side)) elif price in self.quantities: # Total dropped to 0 or below: mark level inactive in O(1) by deleting # from quantities instead of doing an O(L) search inside self.heap. del self.quantities[price] def best_price(self): # Lazy deletion: peel off stale top entries whose price is no longer active. while self.heap: candidate_price = price_from_key(self.heap[0], self.side) if candidate_price in self.quantities: return candidate_price heapq.heappop(self.heap) return None class OrderBook: """Aggregates per-exchange order books and maintains cross-exchange NBBO.""" def __init__(self): # books: {exchange: {"bid": SideBook, "ask": SideBook}} self.books = {} # exchange_best: {(exchange, side): current_best_price_or_None} self.exchange_best = {} # global_heaps[side]: min-heap of (heap_key(price, side), exchange). # Stores candidate exchange tops; stale entries are discarded lazily. self.global_heaps = {BID: [], ASK: []} def add(self, exchange: str, price, quantity, side: str) -> None: if side != BID and side != ASK: raise ValueError(f"side must be 'bid' or 'ask', got {side!r}") # Phase 1: Ensure this exchange has both bid and ask SideBooks. if exchange not in self.books: self.books[exchange] = {BID: SideBook(BID), ASK: SideBook(ASK)} # Phase 2: Apply the quantity delta to this exchange's side book. side_book = self.books[exchange][side] side_book.add(price, quantity) new_best = side_book.best_price() # Phase 3: Update global view only when this exchange's top price changed # (whether it improved, worsened to a deeper level, or became None). old_best = self.exchange_best.get((exchange, side)) if new_best != old_best: self.exchange_best[(exchange, side)] = new_best if new_best is not None: heap_entry = (heap_key(new_best, side), exchange) heapq.heappush(self.global_heaps[side], heap_entry) def get_exchange_bbo(self, exchange: str) -> List[Optional[float]]: # exchange_best is kept up to date on every add(), so queries are O(1). best_bid = self.exchange_best.get((exchange, BID)) best_ask = self.exchange_best.get((exchange, ASK)) return [best_bid, best_ask] def _global_best_on_side(self, side: str): heap = self.global_heaps[side] while heap: key, exchange = heap[0] candidate_price = price_from_key(key, side) # Entry is fresh iff this exchange STILL quotes candidate_price as its top. if self.exchange_best.get((exchange, side)) == candidate_price: return candidate_price # Otherwise that exchange's top moved up, moved down, or became None. heapq.heappop(heap) return None def get_nbbo(self) -> List[Optional[float]]: return [self._global_best_on_side(BID), self._global_best_on_side(ASK)] def run_order_book(operations: List[str], arguments: List[List]) -> List[List[Optional[float]]]: book = OrderBook() results: List[Optional[List[Optional[float]]]] = [] for op, args in zip(operations, arguments): if op == "add": book.add(args[0], args[1], args[2], args[3]) results.append(None) elif op == "get_exchange_bbo": results.append(book.get_exchange_bbo(args[0])) elif op == "get_nbbo": results.append(book.get_nbbo()) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of each stock exchange as having two stacks of sticky notes—one for bids (buy offers, where highest price wins) and one for asks (sell offers, where lowest price wins)—and a national scoreboard showing only the single best sticky note from each exchange to form the NBBO (National Best Bid and Offer, the highest bid and lowest ask across all venues) alongside each venue's BBO (Best Bid and Offer on that one exchange). Whenever a price level is cancelled in the middle of a stack, digging through the stack to rip out that sticky note is slow; instead, we cross that price off in an instant lookup ledger and only peel off crossed-out sticky notes if and when they reach the very top of the stack! This technique is called lazy deletion (marking an item invalid in an O(1) dictionary and deferring physical removal from a heap until it reaches the root).
A naive approach keeps active levels in a single dictionary and rescans all L active levels on every get_exchange_bbo or get_nbbo query, which costs O(L) per read and is far too slow when books are thousands of levels deep. Conversely, keeping prices in a sorted list or heap and eagerly calling list.remove(price) when a deep level empties still requires an O(L) linear search per cancellation. By pairing an authoritative quantities dictionary with a min-heap (a tree-based priority queue that exposes its smallest key in O(1) time and pushes/pops in O(log n) time, using -price for bids so the largest bid comes first) at both the per-exchange level and the global exchange-top level, every update and query avoids linear scans completely.
Let's walk through Example 2's bid side across venues V1 and V2:
1. add("V1", 25, +6, "bid") and add("V1", 24, +9, "bid"): V1's quantities is {25: 6, 24: 9}, V1's best bid is 25, and (-25, "V1") sits on the global bid heap.
2. add("V2", 24.5, +5, "bid"): V2's best bid becomes 24.5, pushing (-24.5, "V2") onto the global bid heap; get_nbbo() peeks (-25, "V1"), confirms V1's current best is 25, and reports 25.
3. add("V1", 25, -6, "bid"): level 25 is deleted from V1's quantities in O(1), V1's local heap pops -25 to expose 24 as V1's new best bid, and (-24, "V1") is pushed onto the global bid heap.
4. On the next get_nbbo(), the global bid heap pops stale (-25, "V1") (since V1's current best is now 24, not 25), sees (-24.5, "V2") next, confirms V2's best is still 24.5, and returns 24.5.
Complexity
Let U be the number of add operations so far, Q the number of queries, L the number of currently active (exchange, side, price) levels, and E the number of exchanges. Here amortized time means the average cost per operation guaranteed over any worst-case sequence of operations (because each lazy pop is paid for up front by the earlier push that created that entry).
add:O(log U)amortized time (O(k log U)worst-case) — Updatingquantitiesandexchange_besttakesO(1)dictionary lookups, and eachaddperforms at most oneheappushinto a side heap and at most oneheappushinto a global heap (each of size at mostU). Ifkstale entries reach the top ofSideBook.heap, popping them takesO(k log U)in that single call, but across allUcalls at mostUentries are ever pushed into side heaps, so total pops cannot exceedU.get_exchange_bbo:O(1)worst-case time — Becauseaddeagerly refreshesexchange_best[(exchange, side)], reading an exchange's BBO is just twoO(1)dictionary lookups with zero heap operations.get_nbbo:O(1)amortized time (O(k log U)worst-case) — Peeking a valid global top takesO(1)time; any stale(key, exchange)entry popped fromglobal_heapswas pushed by an earlieraddand can never be popped again, so total global pops acrossUadds andQqueries are at mostU.- Whole sequence of
Uadds andQqueries:O(U log U + Q)time — Every heap entry is pushed once (O(log U)) and popped at most once (O(log U)), plusO(1)work per query. - Space:
O(L + U)(O(L)after periodic compaction) —quantitiesandexchange_beststore only theLactive levels and2Eexchange tops, while lazy heaps hold up to2Utotal entries in the worst case. To strictly bound memory toO(L)without changing amortized time, rebuild a side heap viaheapifyinO(active)wheneverlen(heap) > 2 * len(quantities)(and rebuildglobal_heaps[side]inO(E)wheneverlen(global_heap) > 2 * E). Note also that ifEis tiny (e.g.,5–15exchanges), scanningexchange_bestacross allEexchanges inO(E)time perget_nbbo()needs no global heap or stale global entries at all; the global heap wins whenEis large orget_nbbocalls vastly outnumber top-of-book changes.
Edge cases
- Unknown exchange or empty side:
exchange_best.get(...)returnsNone, yielding[None, None]for an unseen exchange or[price, None]/[None, price]when only one side has liquidity. - Emptying and later reactivating the same price: Deleting from
quantitiesmarks it inactive, and re-adding pushes a fresh heap key so it is never lost even if its earlier key was already popped. - Over-reduction and zero/negative deltas on missing levels: Bringing a level's total to
0or negative removes it cleanly without storing negative resting debt, andaddwithdelta <= 0on an absent price leaves the book untouched. - Deeper level eventually becoming NBBO: A level added below an exchange's current best does not push to
global_heapsimmediately, but sits inSideBook.heap; once better levels on that exchange empty,new_best != old_bestfires and pushes that deeper level intoglobal_heaps. - Floating-point prices vs. quantities: Prices are only negated (
-price) and compared for exact equality, which is exact in IEEE-754 floats; in real trading systems, integer price ticks and integer lot sizes avoid float rounding drift like0.1 + 0.2 - 0.3 != 0on quantities. - Crossed markets across exchanges: If Exchange
Abids105while ExchangeBasks103, both sides are reported faithfully as[105, 103].
Common mistakes
- Eagerly calling
heap.remove(key)+heapifyon cancellations: That turns every cancellation of a non-top price level into anO(L)scan. - Storing bare prices instead of
(key, exchange)inglobal_heaps: Without knowing which exchange pushed a price,_global_best_on_sidecannot tell whether that entry is still backed by an exchange's current top or whether two exchanges quoted the same price and only one cancelled. - Only pushing to
global_heapswhen an exchange's best improves: When an exchange's top bid of102is cancelled and drops to101,101is worse than102—if you forget to push(heap_key(101), exchange)on worsenings too,101will be missing fromglobal_heaps! - Pushing to
SideBook.heaponly the very first time a price is ever seen: If100empties, gets popped fromSideBook.heap, and later gets refilled, skipping the push leaves100invisible tobest_price(). - Forgetting to un-negate bid keys: Returning
heap[0]directly returns-101instead of101.
Alternative approaches
- Balanced binary search tree per side (
O(log L)worst-case time,O(L)space): A balanced binary search tree (a self-balancing sorted tree such as a red-black tree—std::mapin C++,TreeMapin Java, orSortedDictfromsortedcontainersin Python—that keeps keys ordered and guaranteesO(log L)insert, delete, and min/max lookup) deletes emptied levels eagerly with zero stale memory and strict worst-case latency bounds. It is preferable in low-latency C++/Java engines where worst-case tail latency spikes (O(k log U)from lazy pops) or depth-of-book iteration ("top 5 price levels") matter, whereas Python's standard library lacks a built-in balanced tree, making lazyheapq+dictthe cleanest standard-library choice. - Direct-indexed tick array (
O(1)update,O(tick_gap)scan on top depletion): When prices are integer ticks within a tight intraday range, an array indexed by tick index updates quantities inO(1)with great CPU cache locality, scanning adjacent ticks only when the top level empties.
Follow-up questions
- How would you extend the design to cancel or amend individual orders tracked by an order ID? Add a dictionary
orders: {order_id: [exchange, price, remaining_qty, side]}alongsideOrderBook. Cancellingorder_idlooks up its record inO(1), callsself.add(exchange, price, -remaining_qty, side)to subtract its remaining size from the aggregated level, and deletesorder_idfromorders. Modifying size at the same price callsself.addwithnew_qty - old_qty, while changing an order's price is simply a cancel at the old price followed by a freshaddat the new price (and if per-order FIFO queue priority is also needed for trade matching, each price level can hold a doubly linked list of order nodes). - How could you report the combined resting quantity across every venue currently quoting the NBBO price? Maintain one extra dictionary per side,
global_qty[side][price], updated on everyaddby the actual active change on that venue's level (max(new_qty, 0) - old_qty, deleting the key whenglobal_qtyhits0). Notice a neat invariant: ifPis the NBBO bid, no venue can have an active bid aboveP, so every venue that has any resting bid quantity atPautomatically hasPas its own best bid! Therefore, onceget_nbbo()findsP,global_qty[BID][P]gives the exact cross-venue NBBO size inO(1)time. - How would you adapt the data structures for a single writer thread and many concurrent reader threads? Because
get_nbbo()mutatesglobal_heapswhen popping stale entries, it is not a read-only method and cannot safely run concurrently withaddor otherget_nbbo()calls without synchronization. With a single writer and many readers, have the writer thread run_global_best_on_side(BID)and_global_best_on_side(ASK)at the end of everyaddand publish an immutable snapshot(nbbo_tuple, immutable_bbo_map_or_per_exchange_atomic)via a single reference assignment (or in C++,std::atomic<std::shared_ptr<Snapshot>>or a seqlock, a lightweight sequence-counter lock where writers increment a counter before/after writing and readers retry if the counter was odd or changed). Readers then become wait-freeO(1)reads that never touch any heap. - How would you identify and emit alerts for locked or crossed markets when the global best bid meets or exceeds the global best ask? A market is locked when
best_bid == best_askand crossed whenbest_bid > best_ask(usually because two venues have slightly delayed feeds or routing latency between them). At the end ofadd, whenevernew_best != old_best, compute[best_bid, best_ask] = self.get_nbbo()(which also leaves the quoting venue names sitting atglobal_heaps[BID][0][1]andglobal_heaps[ASK][0][1]); if neither isNoneandbest_bid >= best_ask, classify the state as"LOCKED"or"CROSSED". Track the previous market state so you emit an alert event only on state transitions (e.g.,NORMAL -> CROSSEDorCROSSED -> NORMAL) rather than spamming duplicate alerts on unrelated deep-book updates.
Follow-up questions
- How would you extend the design to cancel or amend individual orders tracked by an order ID?
- How could you report the combined resting quantity across every venue currently quoting the NBBO price?
- How would you adapt the data structures for a single writer thread and many concurrent reader threads?
- How would you identify and emit alerts for locked or crossed markets when the global best bid meets or exceeds the global best ask?
Similar questions
- High-Frequency Stream Buffer and Rolling Metrics Store
- Exact Per-Key Hit Counter Across Threads and Processes
- JavaScript Primitives, Promise Chains, Keyed Collections, and WebSockets
- Turn-Based Console Fleet Game (HarborClash)
- Formula Spreadsheet Engine with Cycle Tracking and Read-Cached Invalidation
- Linear-Time Root-to-Leaf Tree Metrics
More Citadel interview questions
- Optimal Shift Payout with Streak Bonuses Medium
- Minimum Edits for Palindromic Fixed-Size Blocks Medium
- Regional Temperature Regressions and Greedy Predictor Selection for NYC Medium Pro
- One-Shot Batch Selection for Labeling 200 of One Million Feature Vectors Medium Pro
- Binary Classification over Variable-Size Point Clouds with Missing Entries Hard Pro
- Exchange and National Best Quote Aggregator Medium Pro
- Sliding Square Submatrix Sums Medium Pro
- Largest Group Around an Anchor Interval Medium Pro
- Navigating a High-Stakes Engineering Obstacle Medium Pro
- Real-Time Telemetry Ingestion and Sub-2s Alerting Engine Medium Pro