Tackling Long-Winded Data Structure Design Problems Step by Step
Data Structure DesignModel answerLast updated
Describe a repeatable process for data-structure designs that are simple to state but long to code, then apply it to a price-time-priority limit order book.
Some design questions have behavior you can explain in a minute, but the implementation runs to a hundred lines or more with many interacting cases. Think of an in-memory cache with several eviction rules, a rate limiter with multiple windows, or a matching engine.
Explain the process you would follow in a live coding session for a problem like this. Cover:
- How you clarify the operations and constraints before writing code.
- How you model states and transitions.
- How you choose the core data structures.
- How you reason about per-operation time and space complexity.
- Which boundary cases you enumerate.
- How you organize the code and tests to keep bugs down.
Make the answer concrete with a worked example: an order book for one instrument with these operations.
add(id, side, price, qty)adds a buy ("B") or sell ("S") limit order. It first matches against the opposite side, then rests any remainder. It returns the list of fills.cancel(id)removes a resting order and returns whether it existed.best_bid()andbest_ask()return the best price on each side, orNoneif the side is empty.
Assume integer prices, price-then-time priority, and trades executing at the resting order's price.
Hints
Hint 1
Before choosing structures, write down the facts that must always hold between calls (for example, 'an order is indexed if and only if it sits in a price level'). Most bugs in long designs are two structures disagreeing.
Hint 2
Ask what each operation needs: best price, FIFO within a price, and removal of an arbitrary order by id. Pick one structure per need, and consider deleting lazily instead of keeping a heap perfectly in sync.
Hint 3
Put 'remove a resting order' in a single helper, and write an invariant-checking function you can call after every operation in your tests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
In long design problems the algorithms are rarely hard. The bugs come from bookkeeping, where two structures disagree about the same fact. The remedy is a disciplined process: fix the contract, write the invariants, give each need exactly one structure, and test transitions rather than only the happy path.
Step 1: Clarify the contract (2-4 minutes)
Ask only questions that change the design, and state your assumptions aloud.
- API: What is returned on failure,
Falseor an exception? What doesaddreturn? - Semantics: Is priority price-then-time? Do partial fills keep their place in the queue? At whose price does a trade execute?
- Scale: Which operations are hot? In a book, cancels and best-price queries dominate.
- Domain: Are prices integer ticks? Can ids be reused? Can quantity be zero?
For this example: integer prices, ids unique among live orders, qty > 0, trades at the resting price, and a partially filled resting order keeps its queue position.
Step 2: States, transitions and invariants
Draw one entity's life:
NEW -> (no cross) -> RESTING
NEW -> (crosses, leftover > 0) -> fills, then RESTING
NEW -> (crosses, fully filled) -> DONE (never rests)
RESTING -> partly filled -> RESTING (qty reduced, same position)
RESTING -> fully filled/cancel -> GONE
Every arrow is a code path and needs a test. Then write the invariants that hold after every public call:
- An id is in the id index if and only if it is in exactly one price level.
- No empty price level is stored.
- Every non-empty level's price appears in its side's heap (the heap may also hold stale prices).
- The book is not crossed: best bid < best ask.
Step 3: Pick structures by need
| Need | Structure |
|---|---|
| Find an order by id | dict id -> (side, price) |
| FIFO within a price, O(1) removal from the middle | OrderedDict id -> qty per level |
| Level lookup | dict price -> OrderedDict, per side |
| Best price | heap of prices (bids negated) with lazy deletion |
Lazy deletion is the main simplification. A cancel never touches the heap. Stale tops are discarded only when the best price is requested, and validity is checked against the level dict. If a level is emptied and re-created, the heap holds a duplicate price, which is harmless.
Step 4: Complexity
Let L be the number of heap entries and F the number of resting orders an incoming order fills.
add: O((F + 1) log L) amortized. Each fill is O(1) on theOrderedDict, each new level is one push, and each stale pop is paid for by an earlier push.cancel: O(1).best_bid/best_ask: O(log L) amortized.- Space: O(N + P) for N live orders and P pushes. Rebuild the heap if stale entries exceed about half its size.
Step 5: Boundary cases
- Duplicate id, unknown side,
qty <= 0: reject without mutating anything. - Cancel of an unknown or already-filled id: return
False. - An incoming order sweeps several levels.
- An incoming order exactly exhausts a level, which must then be deleted.
- An incoming order is fully filled, so it must not rest.
- A level is emptied and re-created at the same price.
- Empty side: best price is
None.
Step 6: Code organization
- Small private helpers (
_best,_remove) so each invariant is maintained in one place. - Validate first, mutate second, so a failed call leaves no half-applied update.
- An invariant checker written early and called after every operation in tests.
- Tests grouped by transition, plus a randomized test against a naive brute-force book (a list sorted on every query).
Implementation
import heapq
from collections import OrderedDict
class OrderBook:
def __init__(self):
self._levels = {"B": {}, "S": {}} # side -> price -> OrderedDict[id -> qty]
self._heaps = {"B": [], "S": []} # bids stored negated
self._where = {} # id -> (side, price)
def _best(self, side):
heap, levels = self._heaps[side], self._levels[side]
while heap:
p = -heap[0] if side == "B" else heap[0]
if p in levels:
return p
heapq.heappop(heap) # stale
return None
def _remove(self, oid):
side, price = self._where.pop(oid)
level = self._levels[side][price]
del level[oid]
if not level:
del self._levels[side][price]
@staticmethod
def _crosses(side, limit, best):
if best is None:
return False
return best <= limit if side == "B" else best >= limit
def add(self, oid, side, price, qty):
if side not in ("B", "S") or qty <= 0 or oid in self._where:
raise ValueError("invalid order")
opp = "S" if side == "B" else "B"
fills = []
while qty > 0:
best = self._best(opp)
if not self._crosses(side, price, best):
break
level = self._levels[opp][best]
rid, rqty = next(iter(level.items())) # oldest at this price
traded = min(qty, rqty)
fills.append((rid, best, traded))
qty -= traded
if traded == rqty:
self._remove(rid)
else:
level[rid] = rqty - traded # position preserved
if qty > 0:
book = self._levels[side]
if price not in book:
book[price] = OrderedDict()
heapq.heappush(self._heaps[side], -price if side == "B" else price)
book[price][oid] = qty
self._where[oid] = (side, price)
return fills
def cancel(self, oid):
if oid not in self._where:
return False
self._remove(oid)
return True
def best_bid(self):
return self._best("B")
def best_ask(self):
return self._best("S")
def _check(self):
seen = 0
for side, book in self._levels.items():
for price, level in book.items():
assert level
for oid, q in level.items():
assert q > 0 and self._where[oid] == (side, price)
seen += 1
assert seen == len(self._where)
b, a = self.best_bid(), self.best_ask()
assert b is None or a is None or b < a
Common mistakes
- Forgetting to delete an emptied level, so
bestreturns a price with nothing on it. - Letting a fully filled incoming order rest with zero quantity.
- Re-inserting a partially filled resting order, which loses its queue position.
- Mutating state before validation finishes.
- Removing orders in two places with slightly different logic.
- Testing only the happy path instead of each transition.