Designing an Exact Top-Ten Trade Selector
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Architect a software library that ingests raw trade execution records and surfaces the ten largest buy-side entries and ten largest sell-side entries.
Because a request for "the ten largest buys and sells" leaves critical domain semantics open — such as whether ranked items are single fills, parent orders combining split executions, or grouped symbols/accounts; whether size is measured by monetary notional, share volume, or fill count; whether buy and sell rankings are separate; how multi-currency values, reporting time intervals, and equal-score ties behave; and whether records arrive as bounded batch files or live mutable streams — treat these choices as explicit contract decisions rather than assuming one fixed metric. Walk through your ranking contract, exact monetary representation, object boundaries, and bounded-heap selection design.
Scope & Expectations
- Specify the clarifying contract parameters required to make a top-ten buy/sell query unambiguous and deterministic across runs.
- Detail how prices, quantities, and notional totals are parsed and computed without binary floating-point rounding artifacts.
- Separate raw input parsing and validation, time-window filtering, optional entity aggregation, and top-
kselection into clean single-responsibility components. - Explain how a bounded priority queue selects the top ten entries efficiently, and contrast static one-pass selection with live streams where scores can change.
Step-by-step walkthrough
Formalize the ranking rules before writing selection code
Asking for "the ten largest buys and sells" sounds straightforward, yet two engineers reading the exact same execution log can produce completely different answers unless the library first locks down an explicit ranking policy:
Policy dimension Concrete options How it changes the library Ranked unit Individual execution fills, parent orders, or entities (symbol, account, trader) Orders and entities require grouping and summing before ranking Partial-fill handling Each fill counts on its own, or fills sharing an order_idare summed firstSumming by order_idturns trade ranking into an aggregation passSize metric Notional ( quantity * price, total monetary value), sharequantity, or trade countNotional requires exact decimal multiplication with zero rounding loss Buy vs sell partitioning Two separate top- klists, one combined list by gross size, or net(buy - sell)Two lists run two independent selectors; net scores can go negative Multi-currency rules Single-currency input, separate top- kper currency, or FX conversion at a stated rate$1,000USD and¥1,000JPY cannot share one heap without FX rulesReporting interval Full dataset, or half-open [start_ns, end_ns)in UTCNeeds unambiguous boundary inclusion and timestamp precision rules Tie-breaking rule Deterministic secondary key, e.g. scoredescending thencandidate_idascendingWithout a tie rule, heap internals and row arrival order pick winners Shortfall & stream mutability Return < kitems without padding; static batch vs live feed with cancelsLive score increases/decreases require more than a size- kheapBecause raw data alone never settles these choices, capture them in an immutable
RankingPolicyvalue object passed in by the caller. For concrete code below, we illustrate ranking individual trades by exact notional, returning separate buy and sell lists, filtering by a half-open UTC window[start_ns, end_ns), and breaking ties bytrade_idascending, then show what changes when aggregating or streaming.Represent monetary amounts with exact decimal or fixed-point math
Ranking compares scores for
<and==. Using binaryfloatsilently corrupts both individual trade ties and aggregated sums:1. Broken tie on multiplication: Trade A: 3 shares @ $0.10 -> float: 3 * 0.1 = 0.30000000000000004 Trade B: 1 share @ $0.30 -> float: 1 * 0.3 = 0.3 As floats, Trade A falsely beats Trade B even though both notionals are $0.30! 2. Order-dependent aggregation: (0.1 + 0.2) + 0.3 == 0.6000000000000001 (0.3 + 0.2) + 0.1 == 0.6 Shuffling the exact same trades can flip which symbol wins a tie!Use one of two exact representations parsed straight from the raw input strings:
Decimalwith an isolatedlocalcontext():Decimal("3") * Decimal("0.10")isDecimal("0.30"). Python's defaultDecimalcontext keeps 28 significant digits, which is plenty for ordinary trades, but multiplying two 16-digit decimals needs up to 32 digits. Inside awith localcontext() as ctx:block, set a generous precision (sayctx.prec = 50) and trapInexact(ctx.traps[Inexact] = True) so any unexpected rounding raises loudly instead of silently altering rankings — without mutating the caller's thread-localdecimal.getcontext().- Scaled integer minor units (fixed-point arithmetic): Store prices in integer price ticks (e.g.,
$0.0001units) and quantities in integer lots, so notional is an exact integer product. In languages with fixed-width 64-bit signed integers (max~9.22 * 10^18), check whethermax_qty * max_price_tickscan overflow into 128-bit math; Python'sintgrows to arbitrary precision automatically.
from decimal import Decimal, Inexact, localcontext def exact_notional(quantity: Decimal, price: Decimal) -> Decimal: """Multiply quantity and price exactly, raising Inexact if 50 digits are exceeded.""" with localcontext() as ctx: ctx.prec = 50 ctx.traps[Inexact] = True return quantity * priceSeparate parsing, filtering, aggregation, and top-k selection
Give each stage of the pipeline a single, independently testable responsibility:
raw rows ──> TradeParser ──> Trade ──> WindowFilter ──> [EntityAggregator] ──> TopKSelector ──> TopTradesResult │ [start, end) optional sum buy heap (k) top_buys: [...] └──> Reject(line_no, reason) per entity sell heap (k) top_sells: [...] rejects: [...]TradeParser: Validates text fields, parsesDecimalquantities/prices (rejectingNaN/Infinityand non-positive quantities) and UTC integer-nanosecond timestamps, and emits either aTradeor aRejectwith line number and reason.RankingPolicy: Immutable configuration holdingk, window[start_ns, end_ns), currency rule, and aggregation mode.EntityAggregator(optional): Sums exact scores per(side, entity_key)when the contract ranks symbols, accounts, or parent orders.TopKSelector: Pure selection component that sees only genericCandidate(key, score)items — completely decoupled from CSV parsing or trade fields.
from dataclasses import dataclass from decimal import Decimal from enum import Enum from typing import Optional class Side(Enum): BUY = "BUY" SELL = "SELL" @dataclass(frozen=True) class RankingPolicy: k: int = 10 start_ns: Optional[int] = None # inclusive UTC nanosecond lower bound end_ns: Optional[int] = None # exclusive UTC nanosecond upper bound @dataclass(frozen=True) class Trade: trade_id: str side: Side symbol: str quantity: Decimal price: Decimal ts_ns: int # UTC nanoseconds since 1970-01-01T00:00:00Z @dataclass(frozen=True) class Candidate: key: str # trade_id (individual mode) or symbol/order_id (aggregated mode) score: DecimalSelect top k in one pass with a bounded min-heap
Suppose a batch file has
n = 50,000,000trades and we only want the topk = 10. Sorting allntrades takesO(n log n)time andO(n)memory; building a max-heap of allntrades takesO(n + k log n)time and still buffers allntrades in memory.Instead, maintain a min-heap of size at most
kwhose rootheap[0]is always the weakest among thekcandidates currently kept — like a 10-seat VIP lounge where the bouncer only checks whether a newcomer outranks the 10th-best person inside: - Whilelen(heap) < k, push every candidate in (O(log k)). - Once full (len(heap) == k), compare the newcomer againstheap[0]. If the newcomer is stronger,heapq.heapreplaceevictsheap[0]and inserts the newcomer inO(log k); otherwise ignore the newcomer inO(1).To make ties deterministic (
scoredescending, thenkeyascending), define "weaker" inside a wrapper classWorstFirst: candidateais weaker thanbwhena.score < b.score, or whena.score == b.scoreanda.key > b.key(a larger ID loses the tie, so it sits closer toheap[0]and gets evicted first!).import heapq class WorstFirst: """Order candidates so `heap[0]` is always the weakest kept candidate.""" def __init__(self, candidate: Candidate): self.candidate = candidate def __lt__(self, other: "WorstFirst") -> bool: a = self.candidate b = other.candidate if a.score != b.score: return a.score < b.score # Equal score: larger key is weaker so smaller key wins ties. return a.key > b.key def select_top_k(candidates, k: int): """Return up to `k` best candidates ordered by (-score, key) in O(n log k) time and O(k) space.""" if k <= 0: return [] heap = [] for candidate in candidates: entry = WorstFirst(candidate) if len(heap) < k: heapq.heappush(heap, entry) elif heap[0] < entry: heapq.heapreplace(heap, entry) # Popping yields weakest-to-strongest; reverse once of length <= k for best-first output. ordered = [] while heap: ordered.append(heapq.heappop(heap).candidate) ordered.reverse() return orderedLet's trace
select_top_kwithk = 3on six buy candidates (T1=500, T2=1200, T3=300, T4=1200, T5=800, T6=50):Arrival | Action | Kept set in heap | Weakest at heap[0] ---------+---------------------------------+-------------------------+------------------- T1 (500) | heap size 0 < 3 -> push | {T1:500} | T1 (500) T2 (1200)| heap size 1 < 3 -> push | {T1:500, T2:1200} | T1 (500) T3 (300) | heap size 2 < 3 -> push | {T3:300, T1:500, T2:1200}| T3 (300) T4 (1200)| beats root T3 (300) -> replace | {T1:500, T2:1200, T4:1200}| T1 (500) T5 (800) | beats root T1 (500) -> replace | {T5:800, T2:1200, T4:1200}| T5 (800) T6 (50) | loses to root T5 (800) -> drop | {T5:800, T2:1200, T4:1200}| T5 (800) Pop & reverse -> [T2 (1200), T4 (1200), T5 (800)] ("T2" < "T4" breaks the 1200 tie!)Note that string comparison orders
"T10" < "T2"; if trade IDs carry numeric sequence numbers, the contract should specify integer IDs or zero-padded strings. To return top buys and top sells separately, run oneselect_top_kinstance forSide.BUYand one forSide.SELL.Aggregate first whenever candidates span multiple records
If the contract ranks symbols, accounts, or parent orders (summing partial fills), each incoming trade is only a piece of a candidate's score. Running a bounded size-
kheap directly on the raw stream will silently drop winners! Watchk = 1on four trades:Trades in arrival order: (X, 50), (X, 50), (Y, 120), (X, 50) Broken streaming size-1 heap: After (X, 50), (X, 50): heap holds {X: 100} After (Y, 120): Y beats 100 -> X is evicted! Heap holds {Y: 120} After (X, 50): X restarts at 50 (its earlier 100 was lost!) -> loses to Y (120) Wrong output: Y (120) True totals: X = 150, Y = 120 -> X should win!Whenever scores are aggregated, compute all
uentity totals first in a hash map (O(n)time,O(u)memory), and then pass thoseufinalCandidateobjects intoselect_top_k(O(u log k)time,O(k)extra space):def aggregate_notional_by_symbol(trades, side: Side): totals = {} for trade in trades: if trade.side is side: amount = exact_notional(trade.quantity, trade.price) totals[trade.symbol] = totals.get(trade.symbol, Decimal(0)) + amount candidates = [] for symbol, total_notional in totals.items(): candidates.append(Candidate(key=symbol, score=total_notional)) return candidatesDefine half-open time windows and handle imprecise timestamps
Filter time-bounded queries with a half-open interval
[start_ns, end_ns)(start_ns <= trade.ts_ns < end_ns) on UTC integer nanoseconds. Makingstart_nsinclusive andend_nsexclusive ensures back-to-back hourly reports[14:00, 15:00)and[15:00, 16:00)never double-count or drop a trade sitting right on15:00:00.000000000.Coarse feed timestamps or clock skew between venues can still make window membership uncertain near the boundary:
Reporting window: [14:00:00.000, 14:30:00.500) Feed A (millisecond precision): 14:30:00.499 -> strictly inside 14:30:00.500 -> strictly outside (next window) Feed B (truncated to seconds): 14:30:00 -> true event happened in [14:30:00.000, 14:30:01.000), which straddles the 14:30:00.500 cutoff!The contract must state how boundary uncertainty is resolved: align reporting windows to whole seconds (matching the coarsest feed), classify strictly by recorded timestamp and document the convention, or attach a boundary-uncertainty warning. In streaming pipelines, a window's top ten also remains provisional until an event-time watermark confirms no more in-window late trades can arrive.
Support mutable scores under live streams and trade cancellations
A size-
kheap relies on one key invariant: an evicted item can never become a winner later, and a kept item's score never drops. In a live market feed where new fills increase entity totals and trade busts/cancellations decrease them, both assumptions break: 1. Rank #500 can jump to #1 after a block trade, so we must keepscore_by_entityfor alluentities (O(u)memory is unavoidable for exact answers). 2. If rank #2 has a fill canceled and falls out of the top 10, rank #11 must take seat #10 — which a size-10 heap already discarded!Choose the live index structure according to the read-to-write ratio across
uentities:- Hash map + balanced search tree / sorted set (keyed by
(-score, entity_key)): each fill or cancel removes( -old_score, key )and inserts( -new_score, key )inO(log u)time, and reading the topktakesO(k)time. Ideal when dashboards read continuously. - Hash map on write + bounded heap on read: updates do
O(1)dictionary math, and each query runsselect_top_k(map.items(), 10)inO(u log 10)time. Ideal when millions of fills arrive per minute and reports run every few seconds. - Lazy versioned heap: maintain
version_by_entityand push(new_score, key, version)on updates, skipping stale versions when popping; simple for Python'sheapq, with periodicO(u)compaction so deleted entries do not accumulate unboundedly. - Approximate heavy-hitter sketches (such as Space-Saving): if memory must stay bounded below
O(u), updates are positive-only, and an explicit error bound is acceptable.
- Hash map + balanced search tree / sorted set (keyed by
Intuition & how it works
Imagine running a "Top 10 Biggest Single Receipts" board at a busy supermarket checkout: you only need 10 slots on the wall, and if you keep the smallest of those 10 receipts at the bottom (heap[0]), you can ignore any smaller receipt immediately and swap in any bigger receipt in a split second. Now contrast that with "Top 10 Highest-Spending Shoppers Today": you cannot throw away Alice's $50 morning receipt just because ten $100 shoppers came through at noon, because Alice might come back at 5 PM and spend $200! Designing a top-ten trade library rests on making that exact distinction explicit in a ranking contract (RankingPolicy), computing notional (quantity * price, the monetary value of a trade) with exact Decimal arithmetic rather than binary float, separating parsing, filtering, optional aggregation, and selection into single-responsibility components, and applying a bounded min-heap (a binary priority queue capped at k items whose root holds the weakest kept candidate) only after each candidate's score is final.
Why do naive approaches fall short? Multiplying prices in float manufactures fake rank differences (3 * 0.1 == 0.30000000000000004 beats 1 * 0.3 == 0.3) and makes aggregated sums depend on input order. Sorting all n trades wastes O(n log n) time and O(n) memory when k = 10 needs only O(k) space, while running a size-10 heap directly on raw trades drops true winners whenever scores must be summed per symbol/order or revised by trade cancellations.
Here is a concrete k = 3 walkthrough on six buy trades (T1=500, T2=1200, T3=300, T4=1200, T5=800, T6=50) with exact scores and tie-breaking by trade_id ascending:
1. T1 (500), T2 (1200), T3 (300) fill the 3 slots -> heap keeps {T3:300, T1:500, T2:1200}, weakest = T3 (300)
2. T4 (1200) > 300 -> evicts T3 (300) -> heap keeps {T1:500, T2:1200, T4:1200}, weakest = T1 (500)
3. T5 (800) > 500 -> evicts T1 (500) -> heap keeps {T5:800, T2:1200, T4:1200}, weakest = T5 (800)
4. T6 (50) < 800 -> ignored in O(1)
Pop weakest-to-strongest and reverse -> [T2 (1200), T4 (1200), T5 (800)] ("T2" < "T4" breaks the tie)
Key points
- Pin down the ranking contract before coding: Explicitly define what is ranked (individual fills, parent orders summing partial fills — child executions of one order — or symbols/accounts), the score metric, separate buy vs sell lists, currency handling, the
[start_ns, end_ns)UTC window, deterministic tie-breaking, and behavior when fewer thankitems exist. - Keep monetary math exact from string to score: Parse quantities and prices directly into
Decimal(or integer minor units) from raw strings. Multiply inside an isolateddecimal.localcontext()with high precision (e.g.,prec = 50) andtraps[Inexact] = Trueso large exact products never round silently and the caller's thread-local decimal context stays untouched. - Give each object one clear responsibility:
TradeParserconverts text into typedTradeorReject(line_no, reason)records;WindowFilterenforces[start_ns, end_ns); an optionalEntityAggregatorcomputes exact per-entity totals; andTopKSelectorranks genericCandidate(key, score)objects with zero knowledge of file formats. - Use a bounded min-heap of size
kwith tie-aware comparison: Keeping the weakest of the topkatheap[0]selects the bestkout ofnfinal candidates inO(n log k)time andO(k)memory (O(n)time whenk = 10), encoding(score descending, key ascending)directly in__lt__so results never depend on input order. - Aggregate before selecting when candidates span multiple trades: For symbol, account, or parent-order rankings, accumulate exact
Decimaltotals in a hash map first (O(n)time,O(u)space foruentities) and run the size-kheap over theucompleted totals (O(u log k)). - Use half-open UTC windows and explicit mutable-score indexes for streams: Filter with
[start_ns, end_ns)so boundary timestamps never double-count across adjacent windows, and switch from a standalone size-kheap to ascore_by_entitymap plus a balanced tree / sorted set (or on-read heap scan) whenever live fills and cancellations can raise or lower scores.
Common mistakes
- Jumping straight into heap code without clarifying what "top ten" ranks: Returning top 10 individual fills when the interviewer wanted top 10 symbols by aggregated notional solves the wrong problem.
- Computing
quantity * pricein binaryfloator mixing currencies: Floating-point rounding fabricates ties or breaks real ones, and ranking USD alongside JPY without an explicit FX conversion rate compares incompatible units. - Sorting all
nrecords (O(n log n)time,O(n)space) or callingheapifyon allnrecords (O(n)space): Whennis tens of millions of trades on disk andk = 10, buffering every record wastes gigabytes of RAM compared to anO(k)streaming min-heap. - Using
heapq.nlargest(k, trades, key=lambda t: t.notional)without a tie-breaker: On equal scores, Python'snlargestkeeps whichever item appeared earlier in the input, making the output order-dependent. - Comparing string IDs like
"T10"and"T2"blindly: Lexicographical string order puts"T10"before"T2"; numeric sequence IDs should be compared as integers or zero-padded in the contract. - Using closed intervals
[start, end]for reporting windows: A trade landing right on15:00:00gets counted in both[14:00, 15:00]and[15:00, 16:00].
Follow-up questions
- Under what preconditions can a fixed-capacity min-heap of ten elements compute an exact result in a single pass? A bounded min-heap permanently discards any candidate worse than the current 10th-best, which is valid only if every candidate's score is immutable and complete upon arrival. For individual trades with exact notionals, each trade's score is final on sight, so
O(k)memory suffices. For aggregated entities or parent orders, a trade is merely a partial increment: on(X, 50), (X, 50), (Y, 120), (X, 50), a size-1 heap over running totals evictsXat100in favor ofY (120)and forgetsX's earlier100, missingX's true winning total of150. - Which data structures are needed when incoming fills or trade cancellations can raise or lower an entity's running total? When future fills can raise any entity's score, rank #500 can climb into the top 10 at any moment, so exact tracking must retain
score_by_entityfor alluentities (O(u)memory). Furthermore, when a cancellation or bust decreases a top-10 entity's score, the former #11 must promote into #10 — information a size-10 heap already discarded. Pair thescore_by_entitydictionary with a balanced search tree or skip list ordered by(-score, entity_key)forO(log u)updates andO(k)reads, or keep only the dictionary on writes (O(1)) and run the size-10 heap acrossscore_by_entityon each read (O(u log 10)). - How do coarse clock resolutions or server clock drift create ambiguity around time-window cutoffs? Under a half-open window
[14:00:00.000, 14:30:00.500), a feed that truncates timestamps to whole seconds logs14:30:00for any trade occurring in[14:30:00.000, 14:30:01.000), making it impossible to know from the stamp alone whether the trade occurred before or after.500(and clock skew — slight clock drift between servers — creates a similar blur at millisecond or microsecond scales). The policy should explicitly choose whether to align window cutoffs to the coarsest feed precision, classify strictly by recorded timestamp, or flag boundary-ambiguous trades, and in streaming systems wait for an event-time watermark (a timestamp threshold past which late events are no longer expected) before marking a window's top ten final.
Follow-up questions
- Under what preconditions can a fixed-capacity min-heap of ten elements compute an exact result in a single pass?
- Which data structures are needed when incoming fills or trade cancellations can raise or lower an entity's running total?
- How do coarse clock resolutions or server clock drift create ambiguity around time-window cutoffs?
Similar questions
- Domain Contracts for Trade Reconciliation
- Currency Arbitrage Detection and Cycle Recovery
- Progressive C++ Concurrent Queue: Mutex, Spinlock, and Atomic Ring
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination