Top 15 Quant and HFT Coding Interview Problems: What Each One Teaches

- Limit order book uses
TreeMap<price, Deque<Order>>plus a hashmap for O(1) cancel via lazy deletion (tombstone trick) - Lazy deletion is the single most important optimization: it solves median heaps, priority queue cancellation, and LRU eviction in one pattern
- Sliding window VWAP reduces to a deque with running numerator/denominator totals; the follow-up about out-of-order timestamps is the real test
- K-transaction DP generalizes from k=2 to arbitrary k without structural change; special-casing k=2 signals memorization, not understanding
- Quickselect for latency percentiles yields O(n) average; the production-correct answer is C++
nth_element(introselect, O(n) worst-case) - Binary search on the answer solves position sizing: define a monotonic feasibility predicate and binary search the answer range, not the array
- Settlement ordering is topological sort; cycle detection is
processed_count != total_nodesafter Kahn's algorithm finishes
Pick any problem from the list below. Strip the trading context. You've probably seen it on LeetCode. Probably solved it on a Sunday. Probably thought "that was fine."
That's the insight most candidates miss when they start prepping for Jane Street, Citadel Securities, Hudson River Trading, Optiver, or Two Sigma. They assume quant and HFT coding interview problems require finance knowledge. They spend weeks learning about order flow and market microstructure. They read dense papers about execution algorithms. Then they sit down and realize they're being asked about priority queues and sliding windows, just dressed up as order books and price feeds.
The costume is different. The algorithm is the same.
This guide covers software engineer roles, not quant researcher or trader roles. Those interviews lean heavily on probability puzzles, expected value, and mental math. SWE loops at these firms look far closer to a rigorous FAANG loop than to a statistics exam. For the full comparison, see our FAANG vs quant firm interview breakdown.
Here are the 15 problems, what they're really testing, and the implementation detail that separates a passing answer from a failing one.
Wait, I Don't Need to Learn Finance?
Not for the SWE loop. The problems aren't different. The performance expectations are.
An interviewer at HRT or Citadel will ask why you chose TreeMap over HashMap before you write a single line. They'll ask the time complexity of your cancel operation, not just your insert. They expect O(log n) vs O(1) to matter in your reasoning, because at their scale it genuinely does. One bad cache miss pattern can cost real money. They've seen the losses.
The other difference is framing. Problems arrive dressed as market data systems, not as abstract graph or tree puzzles. Recognizing the underlying pattern through the domain costume is the actual test. A candidate who panics at "order book" and a candidate who immediately thinks "sorted map with FIFO queues" are sitting in the same interview. Only one of them is getting an offer.
The 15 Quant Coding Interview Problems
1. Limit Order Book
The single most common quant-firm coding problem. Implement addOrder(side, price, qty), cancelOrder(orderId), and matchOrders() -> fills.
The structure is TreeMap<Long, Deque<Order>> keyed by price, with a companion HashMap<orderId, Order> for O(1) lookup. Bids use a descending map, asks ascending. At each price level, orders queue in arrival order (FIFO priority). Matching walks from best bid against best ask until no overlap.
Cancellation is where most candidates fail. Removing from the middle of a deque is O(n). The correct approach is lazy deletion: mark the order as cancelled in the hashmap, skip it during matching. Cancel becomes O(1). The cost is that matching has to check and skip cancelled orders, which amortizes to acceptable.
This is the interview equivalent of a boss fight. Know your lazy deletion.
2. Median from a Price Stream
Two heaps: a max-heap for the lower half, a min-heap for the upper half. After each insert, balance so sizes differ by at most one. Median is either the top of the larger heap or the average of both tops.
The variant that shows up in trading context is the windowed median: find the median over the last K prices, not all prices seen. Removal from a heap is O(n) unless you use lazy deletion again. The same tombstone trick from problem 1 applies here. A removed counter per heap tracks logical size; stale tops are discarded on read.
Yes, lazy deletion appears twice in the first two problems. No, that is not an accident.
3. Sliding Window VWAP
Volume-weighted average price = sum(price × volume) / sum(volume) over a window of recent trades. Maintain a deque of (price, volume, timestamp) tuples, evict entries outside the window from the front, keep running totals for numerator and denominator.
The follow-up separates good answers from great ones. What if the window is defined by trade count rather than wall time? What if timestamps arrive out of order? What if you're computing this for 1,000 instruments simultaneously? That last question turns a single-deque solution into a per-instrument map of deques, and space complexity becomes O(window_size × num_instruments).
If you get through the follow-ups without flinching, you're having a good interview.
4. Sliding Window Maximum
Given a stream of bid prices, return the maximum bid in each window of size K. Brute force is O(nK). The correct answer is O(n) using a monotonic decreasing deque of indices. Push the new index, pop from the back while the new value exceeds the back's value, pop from the front when the front index falls outside the current window.
This is used directly for rolling high/low calculations in momentum strategies. Store indices in the deque, not values. That's how you check whether the front index has fallen out of the window. It's one of those tricks that looks obvious the moment you see it and completely invisible before that.
5. Circular Ring Buffer
Implement a fixed-capacity buffer with push(item), pop() -> item, isEmpty(), and isFull(). Items are pushed to the back, popped from the front. On overflow, either block, overwrite, or return an error depending on spec.
This is the standard architecture for market data feed handlers. The exchange sends UDP packets; your feed handler writes them into a ring buffer; a reader thread processes asynchronously. The silent corruption bug: never represent the full vs empty state purely by comparing read_pos == write_pos. Both full and empty satisfy that condition. Use a separate size counter or represent capacity as (write - read) % capacity, tracking unsigned overflow carefully.
Getting this wrong means your feed handler silently drops data. In production, you find out via P&L, not logs.
6. Priority Queue with Lazy Deletion
Build a min-heap supporting insert(item, priority), extractMin(), and delete(item). Standard heaps don't support deletion.
Lazy deletion again: maintain a deleted set. On delete, add to set. On extractMin, discard items in the deleted set before returning. This appears for the third time because it's the most commonly missed optimization in quant interviews. A matching engine needs to cancel orders while efficiently finding the best bid or ask. Rebuild the heap on cancellation and your cancel is O(n). You fail the follow-up. The interviewer writes "candidate rebuilt heap on deletion" in their notes and that sentence ends your candidacy.
7. Top K Most Active Symbols
Given a stream of trade events, maintain the K most frequently traded symbols at any given moment. HashMap tracks frequencies; min-heap of size K tracks the current top-K candidates.
The trading-specific follow-up: recent trades matter more than old ones. This transforms the problem into either a sliding window frequency counter or an exponential moving average that decays old activity. The interviewer is checking whether you ask about the recency requirement before coding the simple version. Jumping straight to the static solution without clarifying the time window is the fast path to a weak-hire rating.
Ask. Before. You. Code.
8. Rate Limiter
Allow at most N events per time window T. Sliding window log: maintain a deque of timestamps, evict timestamps older than T on each check, accept if deque size is below N.
In trading, this is the exchange's throttling mechanism on your order submission rate. The O(1) space variant uses two counters and a timestamp for the current window, accepting a small error (~0.003%) in exchange for constant memory per user. Knowing which variant to recommend and why is as important as implementing either one. See the sliding window algorithm guide for both templates.
9. LRU Cache for Quote Data
Implement get(key) and put(key, value) with O(1) time and LRU eviction. HashMap for O(1) lookup, doubly linked list for O(1) move-to-front and tail eviction.
The trading context is a quote cache over a universe of instruments. On a new quote, update the cache. On a miss, fetch from the feed handler. The non-obvious detail is the sentinel (dummy) head and tail nodes that eliminate null checks during insertion and removal. Without them, you'll write five separate null guards and your code will look unconvincing under interview pressure. The full implementation is in our LRU cache guide.
10. Stock Trading with at Most K Transactions
Given daily prices, find the maximum profit using at most K buy-sell pairs. The O(nK) DP: dp[k][i] = max profit using at most k transactions through day i. Optimize by tracking max_so_far = max(dp[k-1][j] - prices[j]) as a running variable, eliminating the inner loop over j.
This is the purest trading-themed DP and appears at Jane Street and Citadel for SWE roles. The insight that earns points: the k=2 solution (LC 123) generalizes cleanly to arbitrary k (LC 188) without a different structure. Candidates who special-case k=2 reveal they memorized rather than understood. Jane Street, more than anywhere else, cares about the difference.
11. Merge Trading Sessions
Given a list of trading session intervals, merge all overlapping sessions. Sort by start time, iterate and merge when current.start <= prev.end, setting merged end to max(prev.end, current.end).
The max() on the end time is the single most common bug here. Without it, a session fully contained inside another truncates the outer session's end. The follow-up: a new session arrives in real time, report overlaps in O(log n). That requires an interval tree. Knowing when to escalate from sort-and-sweep to interval tree is what the interviewer is testing in the second half.
One missing max(). One failed interview. Worth remembering.
12. Topological Sort for Settlement Ordering
Trade A must settle before trade B because A's proceeds fund B's purchase. Given these dependencies, find a valid settlement order or report that none exists.
Kahn's algorithm: compute in-degrees, seed a queue with zero-in-degree nodes, process nodes and decrement in-degrees of neighbors. Cycle detection: if processed_count != total_nodes after the algorithm finishes, a cycle exists and no valid settlement order is possible. This maps more naturally to the clearing-house circular dependency scenario than DFS-based cycle detection does.
13. Quickselect for Latency Percentiles
Given latency samples, find the p50, p95, p99 without sorting the full array. Quickselect: partition around a pivot, recurse only into the partition containing the target rank.
Average O(n), worst O(n²) on adversarial inputs. HFT engineering interviews expect you to know both. The production answer is nth_element in C++ (introselect, guaranteed O(n) worst-case), not a hand-rolled quickselect. Knowing when to defer to a well-engineered standard library function, and why, is the judgment these firms are hiring for. They're not hiring you to reinvent introselect. They're hiring you to know it exists.
14. Protocol Message Parser
Given a byte stream of trade messages in a simplified tag-value format, parse it into structured trade objects. This is a state machine problem: valid tags, accumulate fields, handle delimiters, reject malformed messages.
Every feed handler in production is a protocol parser. The performance variant asks you to parse without heap allocation per field, using index slices or zero-copy string views into the original buffer. That answer signals you've thought about this at the systems level, not just the algorithm level. It's the difference between "I solved the problem" and "I understand why the problem exists."
15. Binary Search on the Answer for Position Sizing
Given N instruments each with a daily capacity limit, find the maximum uniform position size you can take across all instruments without exceeding any individual limit or a total budget.
Define feasible(x): check whether position size x satisfies all constraints. The predicate is monotonic (if x works, all smaller x work too). Binary search the answer space. The key move is recognizing that you're searching a range of possible answers, not an array, and that the check function is a linear greedy scan. See binary search on the answer for the general framework.
Once you've seen this pattern, you see it everywhere. That's the point of this entire list.
Quick Reference
| # | Problem | Core Pattern | Difficulty |
|---|---|---|---|
| 1 | Limit Order Book | Ordered map + FIFO + lazy delete | Hard |
| 2 | Median from Stream | Two heaps + lazy delete | Medium |
| 3 | Sliding Window VWAP | Sliding window + accumulator | Medium |
| 4 | Sliding Window Maximum | Monotonic deque | Medium |
| 5 | Circular Ring Buffer | Modular indexing | Medium |
| 6 | PQ with Lazy Deletion | Heap + tombstone | Medium |
| 7 | Top K Active Symbols | Heap + hashmap | Easy-Medium |
| 8 | Rate Limiter | Sliding window on timestamps | Medium |
| 9 | LRU Quote Cache | Hashmap + doubly linked list | Medium |
| 10 | K-Transaction Trading | DP state machine + running max | Hard |
| 11 | Merge Sessions | Sort + greedy merge | Medium |
| 12 | Settlement Ordering | Kahn's topological sort | Medium |
| 13 | Latency Percentiles | Quickselect / nth_element | Medium |
| 14 | Protocol Parser | State machine | Medium |
| 15 | Position Sizing | Binary search on answer | Medium |
How to Actually Use This List
These 15 problems span the full quant SWE interview space: market data systems (3, 4, 5), order management (1, 2, 6, 9), analytics (7, 13), infrastructure (8, 14), and algorithmic reasoning (10, 11, 12, 15). Don't solve them in isolation. After each one, ask: what trading system would use this as a component?
Most candidates can find the solution. The gap is explaining, under time pressure, why TreeMap over HashMap for the order book price index, or why lazy deletion over heap rebuild for cancellation. Practice the explanation, not just the code. A correct solution delivered silently is worth less than a slightly imperfect solution delivered with clear reasoning.
If you want to practice that explanation under realistic conditions, SpaceComplexity runs voice-based mock interviews where you walk through problems like these out loud and receive rubric-based feedback on your reasoning, not just your solution. That's the gap these firms are actually testing.