Implement a Price-Time Priority Limit Order Book With Cancels
Last updated: November 29, 2026
Quick Overview
Implement a limit order book that supports adding limit orders (which match immediately against the opposite side under price-time priority and rest any remainder), cancelling resting orders by id, and querying the best bid and ask.
Millennium
November 29, 20260
0
0 solved
Implement a limit order book that supports adding limit orders (which match immediately against the opposite side under price-time priority and rest any remainder), cancelling resting orders by id, and querying the best bid and ask.
Systematic and execution teams at a multi-strategy fund simulate exchange matching in backtesters and internal crossing logic, so an order book is a core onsite exercise for trading infrastructure roles. Interviewers look for correct priority rules, efficient cancels and a clear discussion of the data structures you would use in C++ for latency.
What the Interviewer Expects
- Matches incoming orders against the best opposite price while prices cross
- Preserves FIFO order within a price level
- Supports O(1) cancel via an order id index (lazy deletion or intrusive list)
- Keeps best bid and ask retrieval cheap
- Returns trade records with both order ids, price and quantity
- Discusses production layout: arrays indexed by tick, intrusive lists, no heap allocation on the hot path
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you support order modify, and when does it lose time priority?
- How do you add market orders and immediate-or-cancel orders?
- How would you lay this out in C++ for a few hundred nanoseconds per update?
- How would you rebuild a book from an exchange's full-depth feed instead of matching yourself?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
add(id, side, price, qty) returns fills; a buy matches asks priced at or below its limit, best price first, oldest first within a level. cancel(id) removes a resting order. top() returns (best b...
High-Level Design
Per side: a dict from price to a deque of [id, qty] entries, plus a heap of prices (negated for bids) to find the best level. An orders dict maps id to its entry so cancel just zeroes the quantity...