Limit Order Book Price-Time Matching
Asked of: Software Engineer
Last updated

What's being tested
This tests stateful stream processing with priority queues / ordered maps and FIFO queues to implement a limit order book. You must preserve price-time priority, handle partial fills, and update mutable book state cleanly across a sequence of buy/sell orders.
Patterns & templates
-
Use two books: bids sorted by highest price first, asks sorted by lowest price first; each price level stores a FIFO queue.
-
Matching condition: buy crosses when
buy.price >= bestAsk; sell crosses whensell.price <= bestBid; loop until order filled or no cross. -
Store per-price orders in
dequeto preserve time priority; consume from the front and append residual incoming orders at the back. -
Use
TreeMap,SortedDict, heap plus lazy deletion, or ordered balanced BST; targetO(log P + F)per order, wherePis price levels andFfills. -
Keep mutable fields explicit:
remaining_qty,order_id,timestamp,side,price; never mutate price or time priority after insertion. -
Remove empty price levels immediately after the last order at that level is filled; stale levels cause wrong best bid/ask behavior.
-
Factor helpers like
match(order, opposite_book),add_to_book(order, same_side_book), andbest_price(book)for testable, readable code.
Common pitfalls
Pitfall: Matching by best timestamp globally instead of best price first; priority is price, then FIFO within the same price.
Pitfall: Forgetting partial fills; both the incoming order and resting order can have residual quantity after each trade.
Pitfall: Using a plain hash map for prices without an efficient best-price lookup, causing
O(P)scans per incoming order.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Featured in interview prep guides
Practice questions
Related concepts
- Crypto Trading And Order Routing SystemsSystem Design
- Auctions, Ticketing, And Real-Time MessagingSystem Design
- Greedy, Heaps, And Scheduling OptimizationCoding & Algorithms
- Pricing, Demand, And Capacity OptimizationAnalytics & Experimentation
- Intervals, Sliding Windows, And Time-Ordered StateCoding & Algorithms
- Time Interval Overlap And Sweep-Line AlgorithmsCoding & Algorithms