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 (int or float): price level on that venue.
    • quantity (int or float): signed volume change applied to (exchange, side, price). Positive values add resting volume; negative values cancel or fill existing volume; 0 leaves 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 than 0. Whenever an update brings a level's total volume to 0 or below, that level is removed completely (never stored as a negative balance, so a later positive "add" starts fresh from 0).
    • Appends None to the output list.
  • "get_exchange_bbo" with [exchange]:
    • Appends [best_bid, best_ask] for exchange, where best_bid is the highest active "bid" price on exchange and best_ask is the lowest active "ask" price on exchange.
    • If a side has no active price levels—or exchange has never appeared—return None for that side.
  • "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, using None for 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.

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" quotes 50.0 bid and 50.5 ask, 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" at 50.2 and the lowest ask is "BATS" at 50.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 at 25 and "V2" holds the only ask at 26, giving [25, 26]. Applying -6 at ("V1", "bid", 25) depletes that level to 0, so "V1" falls back to its deeper bid 24 ([24, None]), while the cross-venue best bid shifts to "V2" at 24.5 ([24.5, 26]).

Constraints

  • 0 <= len(operations) == len(arguments) <= 100,000
  • side is always "bid" or "ask"
  • exchange is a non-empty string
  • price > 0 (int or float); quantity is a signed int or float
  • Aim for O(log U) amortized time per "add" and O(1) worst-case / amortized time per BBO / NBBO query, where U is the number of "add" operations

Step-by-step walkthrough

  1. 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): - quantity is a signed change (delta) to the resting quantity at (exchange, side, price) and add returns None. - A price level is active only while its total quantity is strictly greater than 0. If a negative quantity brings the total to 0 (or below), the level is removed completely; a later positive add starts fresh from 0. - If a side has no active price levels—or an exchange has never been seen—its best price is None.

  2. Why scanning every price level is too slow

    A simple brute-force model stores one dictionary (exchange, side, price) -> total_qty and scans every active key on each get_exchange_bbo or get_nbbo call.

    Updating the dictionary takes O(1) time, which is great, but every query takes O(L) time where L is 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 answer get_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!

  3. 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):

    1. quantities dictionary ({price: total_qty}): The single source of truth. Only active prices (total_qty > 0) live in this dictionary.
    2. heap list (a min-heap of price keys): Orders candidate prices. Python's heapq always puts the smallest number at heap[0], so ask prices go in directly (price), while bid prices go in negated (-price) so the largest bid sits at heap[0].

    When a price level drops to 0, we delete it from quantities in O(1) time and leave its old key sitting inside heap. We only pop stale keys when they actually reach heap[0] inside best_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 -101 entry was popped? Because 101 is not in quantities, we push -101 when reactivating it. Having two -101 entries in heap is completely harmless: while 101 is active both represent the valid price 101, and once 101 empties again best_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 None
    
  4. Part 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 than price alone? Because to check whether a global heap entry is still fresh, we need to ask: "Is exchange STILL quoting price as its current best on this side?" We verify that in O(1) time by checking self.exchange_best.get((exchange, side)) == candidate_price.

    And notice when we update exchange_best and push to global_heaps: whenever new_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 (or None)!

    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)]
    
  5. Wire up the operation runner

    The judge passes parallel lists operations and arguments. Each "add" appends None to 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 results
    
  6. Trace Example 2 step by step

    Let's trace Example 2 (V1 posting two bid levels, V2 posting a bid and an ask, and V1'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]
    
  7. Part 3: Amortized vs. worst-case complexity

    Let U be the total number of add calls so far and Q be the number of queries: - Every add pushes at most 1 entry onto a SideBook heap and at most 1 entry onto a global_heaps heap (<= 2U pushes 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 a while loop pops a stale entry later—whether inside add or get_nbbo—that entry spends its coin to pay for its own O(log U) heappop, and can never be popped again! - Therefore, U updates and Q queries take O(U log U + Q) total time: - add: O(log U) amortized, O(k log U) worst-case if k stale entries surface at once. - get_exchange_bbo: O(1) worst-case (two dictionary lookups in exchange_best). - get_nbbo: O(1) amortized, O(k log U) worst-case if k stale global entries surface at once.

  8. 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) — Updating quantities and exchange_best takes O(1) dictionary lookups, and each add performs at most one heappush into a side heap and at most one heappush into a global heap (each of size at most U). If k stale entries reach the top of SideBook.heap, popping them takes O(k log U) in that single call, but across all U calls at most U entries are ever pushed into side heaps, so total pops cannot exceed U.
  • get_exchange_bbo: O(1) worst-case time — Because add eagerly refreshes exchange_best[(exchange, side)], reading an exchange's BBO is just two O(1) dictionary lookups with zero heap operations.
  • get_nbbo: O(1) amortized time (O(k log U) worst-case) — Peeking a valid global top takes O(1) time; any stale (key, exchange) entry popped from global_heaps was pushed by an earlier add and can never be popped again, so total global pops across U adds and Q queries are at most U.
  • Whole sequence of U adds and Q queries: O(U log U + Q) time — Every heap entry is pushed once (O(log U)) and popped at most once (O(log U)), plus O(1) work per query.
  • Space: O(L + U) (O(L) after periodic compaction) — quantities and exchange_best store only the L active levels and 2E exchange tops, while lazy heaps hold up to 2U total entries in the worst case. To strictly bound memory to O(L) without changing amortized time, rebuild a side heap via heapify in O(active) whenever len(heap) > 2 * len(quantities) (and rebuild global_heaps[side] in O(E) whenever len(global_heap) > 2 * E). Note also that if E is tiny (e.g., 5–15 exchanges), scanning exchange_best across all E exchanges in O(E) time per get_nbbo() needs no global heap or stale global entries at all; the global heap wins when E is large or get_nbbo calls vastly outnumber top-of-book changes.

Edge cases

  • Unknown exchange or empty side: exchange_best.get(...) returns None, 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 quantities marks 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 0 or negative removes it cleanly without storing negative resting debt, and add with delta <= 0 on 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_heaps immediately, but sits in SideBook.heap; once better levels on that exchange empty, new_best != old_best fires and pushes that deeper level into global_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 like 0.1 + 0.2 - 0.3 != 0 on quantities.
  • Crossed markets across exchanges: If Exchange A bids 105 while Exchange B asks 103, both sides are reported faithfully as [105, 103].

Common mistakes

  • Eagerly calling heap.remove(key) + heapify on cancellations: That turns every cancellation of a non-top price level into an O(L) scan.
  • Storing bare prices instead of (key, exchange) in global_heaps: Without knowing which exchange pushed a price, _global_best_on_side cannot 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_heaps when an exchange's best improves: When an exchange's top bid of 102 is cancelled and drops to 101, 101 is worse than 102—if you forget to push (heap_key(101), exchange) on worsenings too, 101 will be missing from global_heaps!
  • Pushing to SideBook.heap only the very first time a price is ever seen: If 100 empties, gets popped from SideBook.heap, and later gets refilled, skipping the push leaves 100 invisible to best_price().
  • Forgetting to un-negate bid keys: Returning heap[0] directly returns -101 instead of 101.

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::map in C++, TreeMap in Java, or SortedDict from sortedcontainers in Python—that keeps keys ordered and guarantees O(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 lazy heapq + dict the 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 in O(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]} alongside OrderBook. Cancelling order_id looks up its record in O(1), calls self.add(exchange, price, -remaining_qty, side) to subtract its remaining size from the aggregated level, and deletes order_id from orders. Modifying size at the same price calls self.add with new_qty - old_qty, while changing an order's price is simply a cancel at the old price followed by a fresh add at 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 every add by the actual active change on that venue's level (max(new_qty, 0) - old_qty, deleting the key when global_qty hits 0). Notice a neat invariant: if P is the NBBO bid, no venue can have an active bid above P, so every venue that has any resting bid quantity at P automatically has P as its own best bid! Therefore, once get_nbbo() finds P, global_qty[BID][P] gives the exact cross-venue NBBO size in O(1) time.
  • How would you adapt the data structures for a single writer thread and many concurrent reader threads? Because get_nbbo() mutates global_heaps when popping stale entries, it is not a read-only method and cannot safely run concurrently with add or other get_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 every add and 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-free O(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_ask and crossed when best_bid > best_ask (usually because two venues have slightly delayed feeds or routing latency between them). At the end of add, whenever new_best != old_best, compute [best_bid, best_ask] = self.get_nbbo() (which also leaves the quoting venue names sitting at global_heaps[BID][0][1] and global_heaps[ASK][0][1]); if neither is None and best_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 -> CROSSED or CROSSED -> NORMAL) rather than spamming duplicate alerts on unrelated deep-book updates.

Follow-up questions

Similar questions

More Citadel interview questions

All 90 Citadel questions →