What a quant-developer coding round looks for
A typical round is 45–60 minutes for one to three problems. The problems are rarely exotic: they are standard data-structure problems dressed in market data (trades, quotes, order books, feeds). What separates candidates is:
- Pinning down the spec in two minutes. Is the window inclusive? How are ties broken? Can the input be empty? Are prices floats or integer ticks?
- Naming the data structure before writing code. "A deque with running sums", "a heap of iterators", "a monotonic deque". Saying this first lets the interviewer redirect you before you spend ten minutes.
- Stating complexity unprompted, per operation for streaming problems (amortised where relevant) and in memory as well as time.
- Testing by hand: one normal case, one edge case (empty, single element, ties, boundary of the window), read aloud.
- Handling the follow-up, which is where most of the signal is: "now make it thread-safe", "now the data does not fit in memory", "now it must be O(1) per update".
How to use these sets
Each set has three problems and a total target time. Write a working solution in a plain editor (no autocomplete, no running until you think you are done), then run it against the tests given. Every solution below was run with the tests shown; the outputs are real. Compare your choice of structure and your edge-case handling with the solution, not only whether it passes.
Worked example
Set A, problem 1 (target 12 minutes): VWAP over a time window
Trades arrive in timestamp order as (ts, price, qty). Implement on_trade(ts, price, qty) and vwap(now), where vwap(now) is the volume-weighted average price of trades with , or None if there are none. Both operations should be fast on a stream of millions of trades.
Show solutionHide solution
Clarify first. Timestamps are non-decreasing; now never goes backwards; the window is half-open . Ask whether price is a float or integer ticks (it changes the follow-up).
Structure. A deque of trades in the window plus running sums and . Each trade is appended once and popped once, so both operations are amortised ; memory is .
from collections import deque
class WindowVWAP:
def __init__(self, window):
self.window = window
self.trades = deque() # (ts, price, qty)
self.pv = 0.0 # sum of price * qty in the window
self.vol = 0 # sum of qty in the window
def _evict(self, now):
while self.trades and self.trades[0][0] <= now - self.window:
_, p, q = self.trades.popleft()
self.pv -= p * q
self.vol -= q
def on_trade(self, ts, price, qty):
self.trades.append((ts, price, qty))
self.pv += price * qty
self.vol += qty
self._evict(ts)
def vwap(self, now):
self._evict(now)
return self.pv / self.vol if self.vol else None
w = WindowVWAP(window=10)
w.on_trade(0, 100.0, 10)
w.on_trade(4, 101.0, 30)
print(w.vwap(5)) # (1000 + 3030) / 40
w.on_trade(10, 99.0, 20) # the trade at t=0 leaves: 0 <= 10 - 10
print(w.vwap(10)) # (3030 + 1980) / 50
print(w.vwap(30)) # empty window
Output:
100.75
100.2
None
The solution also passed 300 randomised comparisons against a brute-force recomputation over the window.
Follow-ups.
- Floating-point drift: subtracting from
pvfor hours accumulates rounding error. Keep prices as integer ticks sopvis an exact integer, or periodically recompute the sum from the deque. - Window by count instead of time: same structure, evict when
len > N. - Many symbols: a dict from symbol to
WindowVWAP;vwapon an idle symbol must still evict, which is whyvwaptakesnow.
Worked example
Set A, problem 2 (target 8 minutes): top k symbols by volume
Given a list of (symbol, qty) trades and an integer , return the symbols with the largest total volume as (symbol, volume) pairs, largest first, ties broken alphabetically.
Show solutionHide solution
Structure. Aggregate with a hash map in , then select the top of distinct symbols with a size- heap in . Sorting all symbols is and is fine to mention as the simple version; the heap matters when is large and small.
from collections import Counter
import heapq
def top_k_by_volume(trades, k):
vol = Counter()
for sym, qty in trades:
vol[sym] += qty
return heapq.nsmallest(k, vol.items(), key=lambda kv: (-kv[1], kv[0]))
t = [("AAPL", 100), ("MSFT", 300), ("AAPL", 250),
("TSLA", 50), ("MSFT", 50), ("NVDA", 320)]
print(top_k_by_volume(t, 2))
print(top_k_by_volume(t, 3))
Output:
[('AAPL', 350), ('MSFT', 350)]
[('AAPL', 350), ('MSFT', 350), ('NVDA', 320)]
AAPL and MSFT tie on 350 and come out alphabetically, which is exactly the case to test aloud. nsmallest with the key gives "largest volume, then smallest name" in one pass. It passed 300 randomised checks against a full sort.
Follow-ups.
- Streaming, query top-k at any time: keep the counts in a dict and answer queries with the heap selection ( per query), or, if queries dominate, maintain an order-statistics structure (a sorted container keyed by ) for updates.
- Approximate, bounded memory over billions of trades: Count-Min sketch plus a heap of candidates, or the Space-Saving algorithm; say that the answer is then approximate with a bounded error.
- Distributed: aggregate per shard, then merge counts. Merging only each shard's local top-k is wrong in general, since a symbol can be eleventh everywhere and first overall.
Worked example
Set A, problem 3 (target 10 minutes): merge sorted feeds
You have feeds, each a list of (ts, payload) sorted by timestamp. Produce a single stream sorted by timestamp, yielding (ts, feed_index, payload). On equal timestamps, the lower feed index goes first, and messages from the same feed keep their order. Feeds may be empty, and the total size may be too large to concatenate and sort.
Show solutionHide solution
Structure. A min-heap holding the current head of each feed, keyed by (ts, feed_index). Pop the smallest, push that feed's next message. Time , memory , and it works on iterators, so the feeds can be files or sockets. Concatenating and sorting is and needs everything in memory.
import heapq
def merge_feeds(feeds):
heap = []
for i, feed in enumerate(feeds):
it = iter(feed)
first = next(it, None)
if first is not None:
heap.append((first[0], i, first[1], it))
heapq.heapify(heap)
while heap:
ts, i, payload, it = heap[0]
yield ts, i, payload
nxt = next(it, None)
if nxt is None:
heapq.heappop(heap)
else:
heapq.heapreplace(heap, (nxt[0], i, nxt[1], it))
a = [(1, "a1"), (4, "a4"), (9, "a9")]
b = [(2, "b2"), (4, "b4")]
c = []
d = [(0, "d0"), (10, "d10")]
print(list(merge_feeds([a, b, c, d])))
Output:
[(0, 3, 'd0'), (1, 0, 'a1'), (2, 1, 'b2'), (4, 0, 'a4'), (4, 1, 'b4'), (9, 0, 'a9'), (10, 3, 'd10')]
The bug to avoid. Pushing (ts, payload, it) without the feed index makes Python compare payloads on a timestamp tie, and then iterators if payloads tie too, which raises TypeError. The index makes every key unique, so the heap never compares further, and it implements the tie rule. Because each feed has at most one entry in the heap, its own order is preserved automatically. The function passed 300 randomised checks against a stable sort.
Follow-ups. heapq.merge(*feeds, key=...) is the library version (say you know it, then write the heap yourself if asked). For two feeds a two-pointer merge is . In C++ the same idea uses std::priority_queue with a comparator that is std::greater on (ts, index).
Worked example
Set B, problem 1 (target 10 minutes): per-client order rate limiter
A gateway must reject any order that would give a client more than accepted orders in any window milliseconds. Implement allow(client, t), called with non-decreasing , returning whether the order is accepted.
Show solutionHide solution
Clarify. Do rejected orders count towards the limit? (Here, no.) Is the window sliding or fixed buckets? (Sliding: fixed buckets let a client send orders across a bucket boundary, which is a good point to raise.)
Structure. Per client, a deque of accepted timestamps (a "sliding log"). Evict expired timestamps, then accept if fewer than remain. Amortised per call, memory per client.
from collections import deque, defaultdict
class RateLimiter:
def __init__(self, limit, window_ms):
self.limit = limit
self.window = window_ms
self.sent = defaultdict(deque) # client -> accepted timestamps
def allow(self, client, t):
q = self.sent[client]
while q and q[0] <= t - self.window:
q.popleft()
if len(q) < self.limit:
q.append(t)
return True
return False
rl = RateLimiter(limit=3, window_ms=1000)
print([rl.allow("c1", t) for t in [0, 100, 200, 300, 999, 1000, 1001, 1100]])
Output:
[True, True, True, False, False, True, False, True]
Trace the boundary cases aloud: at the window still holds 0, 100 and 200, so it is rejected; at the order at 0 leaves, so it is accepted; at the window holds 100, 200 and 1000; at the order at 100 has left. The class passed 300 randomised checks against a brute-force count.
Follow-ups. A token bucket uses memory per client and allows bursts up to the bucket size; it is the usual production choice and is easy to describe (refill rate , capacity ). For many threads, shard clients across threads rather than lock one dict. Exchange-imposed limits are usually enforced in the gateway before the order leaves, because breaching them can get the session disconnected.
Worked example
Set B, problem 2 (target 10 minutes): rolling maximum
Given a list of prices and a window length , return the maximum of every window of consecutive prices, in total time.
Show solutionHide solution
Structure. A monotonic deque of indices whose prices are strictly decreasing from front to back. A new price pops every smaller-or-equal price from the back (they can never be a maximum again while the new one is in the window), and the front is dropped when it leaves the window. Each index enters and leaves once: time, memory. A heap gives ; recomputing each window is .
from collections import deque
def rolling_max(prices, k):
dq, out = deque(), []
for i, p in enumerate(prices):
while dq and prices[dq[-1]] <= p:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
out.append(prices[dq[0]])
return out
print(rolling_max([5, 3, 4, 1, 2, 6, 0], 3))
Output:
[5, 4, 4, 6, 6]
Store indices, not prices: the expiry test needs positions. It passed 300 randomised checks against max(prices[i:i+k]).
Follow-ups. Rolling minimum: flip the comparison. Rolling drawdown from the window high: price / rolling_max - 1. Time-based windows: store (ts, price) and expire by timestamp, as in the VWAP problem.
Worked example
Set B, problem 3 (target 15 minutes): top of book from level updates
A feed sends price-level updates (side, price, qty) with side "B" or "S"; qty = 0 deletes the level, otherwise it sets the level's quantity. After each update, report (best_bid, best_ask), with None for an empty side. Prices are integer ticks.
Show solutionHide solution
Structure. Per side, a dict from price to quantity (the truth) plus a heap of prices (bids negated) with lazy deletion: a deleted level is left in the heap and discarded when it reaches the top. Updates are , best-price queries amortised .
import heapq
class TopOfBook:
def __init__(self):
self.levels = {"B": {}, "S": {}}
self.heaps = {"B": [], "S": []} # bids stored as negative prices
def set(self, side, price, qty):
lv = self.levels[side]
if qty == 0:
lv.pop(price, None)
return
if price not in lv:
heapq.heappush(self.heaps[side], -price if side == "B" else price)
lv[price] = qty
def _top(self, side):
h, lv = self.heaps[side], self.levels[side]
while h:
p = -h[0] if side == "B" else h[0]
if p in lv:
return p
heapq.heappop(h) # stale entry for a deleted level
return None
def best(self):
return self._top("B"), self._top("S")
b = TopOfBook()
for msg in [("B", 9950, 5), ("B", 9960, 2), ("S", 9970, 4), ("S", 9980, 1),
("B", 9960, 0), ("S", 9970, 0), ("B", 9960, 7)]:
b.set(*msg)
print(msg, b.best())
Output:
('B', 9950, 5) (9950, None)
('B', 9960, 2) (9960, None)
('S', 9970, 4) (9960, 9970)
('S', 9980, 1) (9960, 9970)
('B', 9960, 0) (9950, 9970)
('S', 9970, 0) (9950, 9980)
('B', 9960, 7) (9960, 9980)
It passed 300 randomised update sequences against max/min over the dicts.
Follow-ups the interviewer will push on.
- Heap growth: a level deleted and re-added many times leaves duplicates. Rebuild the heap when it exceeds, say, twice the live level count.
- Full depth, ordered: a sorted container (or, in C++,
std::map<int, int, std::greater<>>for bids) gives ordered iteration at per update. - Low latency: prices cluster near the touch, so production books often use an array indexed by tick offset from a reference price, giving updates and a cached best index that is rescanned only when the best level empties.
- Crossed book (best bid at or above best ask): with a single venue's feed it signals a missed message, so trigger recovery rather than trading on it.
Knowledge check
You merge k sorted feeds with a heap of (ts, payload, iterator) tuples. Two feeds have a message with the same timestamp and identical payloads. What happens in Python?
Knowledge check
Each of 8 shards reports its local top 10 symbols by volume, and you merge those 80 entries to get a global top 10. Is this correct?
Knowledge check
In the monotonic-deque rolling maximum, why is the total time O(n) even though each step has a while loop?
Key takeaways
- Most QD coding problems are a standard structure plus a market-data story: deque with running sums (windows), heap (top-k, k-way merge), monotonic deque (rolling extrema), dict plus heap with lazy deletion (books).
- Spend the first two minutes on the spec: window boundaries, tie rules, empty input, float or integer prices.
- State per-operation and amortised complexity, and memory, without being asked.
- Test boundaries aloud: the trade exactly old, tied volumes, an empty feed.
- Prepare the follow-ups: floating-point drift, bounded memory, distributed aggregation, and the low-latency version.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).