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-k selection 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

  1. 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_id are summed first Summing by order_id turns trade ranking into an aggregation pass
    Size metric Notional (quantity * price, total monetary value), share quantity, or trade count Notional requires exact decimal multiplication with zero rounding loss
    Buy vs sell partitioning Two separate top-k lists, 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-k per currency, or FX conversion at a stated rate $1,000 USD and ¥1,000 JPY cannot share one heap without FX rules
    Reporting interval Full dataset, or half-open [start_ns, end_ns) in UTC Needs unambiguous boundary inclusion and timestamp precision rules
    Tie-breaking rule Deterministic secondary key, e.g. score descending then candidate_id ascending Without a tie rule, heap internals and row arrival order pick winners
    Shortfall & stream mutability Return < k items without padding; static batch vs live feed with cancels Live score increases/decreases require more than a size-k heap

    Because raw data alone never settles these choices, capture them in an immutable RankingPolicy value 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 by trade_id ascending, then show what changes when aggregating or streaming.

  2. Represent monetary amounts with exact decimal or fixed-point math

    Ranking compares scores for < and ==. Using binary float silently 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:

    • Decimal with an isolated localcontext(): Decimal("3") * Decimal("0.10") is Decimal("0.30"). Python's default Decimal context keeps 28 significant digits, which is plenty for ordinary trades, but multiplying two 16-digit decimals needs up to 32 digits. Inside a with localcontext() as ctx: block, set a generous precision (say ctx.prec = 50) and trap Inexact (ctx.traps[Inexact] = True) so any unexpected rounding raises loudly instead of silently altering rankings — without mutating the caller's thread-local decimal.getcontext().
    • Scaled integer minor units (fixed-point arithmetic): Store prices in integer price ticks (e.g., $0.0001 units) 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 whether max_qty * max_price_ticks can overflow into 128-bit math; Python's int grows 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 * price
    
  3. Separate 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, parses Decimal quantities/prices (rejecting NaN/Infinity and non-positive quantities) and UTC integer-nanosecond timestamps, and emits either a Trade or a Reject with line number and reason.
    • RankingPolicy: Immutable configuration holding k, 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 generic Candidate(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: Decimal
    
  4. Select top k in one pass with a bounded min-heap

    Suppose a batch file has n = 50,000,000 trades and we only want the top k = 10. Sorting all n trades takes O(n log n) time and O(n) memory; building a max-heap of all n trades takes O(n + k log n) time and still buffers all n trades in memory.

    Instead, maintain a min-heap of size at most k whose root heap[0] is always the weakest among the k candidates currently kept — like a 10-seat VIP lounge where the bouncer only checks whether a newcomer outranks the 10th-best person inside: - While len(heap) < k, push every candidate in (O(log k)). - Once full (len(heap) == k), compare the newcomer against heap[0]. If the newcomer is stronger, heapq.heapreplace evicts heap[0] and inserts the newcomer in O(log k); otherwise ignore the newcomer in O(1).

    To make ties deterministic (score descending, then key ascending), define "weaker" inside a wrapper class WorstFirst: candidate a is weaker than b when a.score < b.score, or when a.score == b.score and a.key > b.key (a larger ID loses the tie, so it sits closer to heap[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 ordered
    

    Let's trace select_top_k with k = 3 on 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 one select_top_k instance for Side.BUY and one for Side.SELL.

  5. 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-k heap directly on the raw stream will silently drop winners! Watch k = 1 on 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 u entity totals first in a hash map (O(n) time, O(u) memory), and then pass those u final Candidate objects into select_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 candidates
    
  6. Define 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. Making start_ns inclusive and end_ns exclusive ensures back-to-back hourly reports [14:00, 15:00) and [15:00, 16:00) never double-count or drop a trade sitting right on 15: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.

  7. Support mutable scores under live streams and trade cancellations

    A size-k heap 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 keep score_by_entity for all u entities (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 u entities:

    • 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 ) in O(log u) time, and reading the top k takes O(k) time. Ideal when dashboards read continuously.
    • Hash map on write + bounded heap on read: updates do O(1) dictionary math, and each query runs select_top_k(map.items(), 10) in O(u log 10) time. Ideal when millions of fills arrive per minute and reports run every few seconds.
    • Lazy versioned heap: maintain version_by_entity and push (new_score, key, version) on updates, skipping stale versions when popping; simple for Python's heapq, with periodic O(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.

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 than k items 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 isolated decimal.localcontext() with high precision (e.g., prec = 50) and traps[Inexact] = True so large exact products never round silently and the caller's thread-local decimal context stays untouched.
  • Give each object one clear responsibility: TradeParser converts text into typed Trade or Reject(line_no, reason) records; WindowFilter enforces [start_ns, end_ns); an optional EntityAggregator computes exact per-entity totals; and TopKSelector ranks generic Candidate(key, score) objects with zero knowledge of file formats.
  • Use a bounded min-heap of size k with tie-aware comparison: Keeping the weakest of the top k at heap[0] selects the best k out of n final candidates in O(n log k) time and O(k) memory (O(n) time when k = 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 Decimal totals in a hash map first (O(n) time, O(u) space for u entities) and run the size-k heap over the u completed 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-k heap to a score_by_entity map 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 * price in binary float or 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 n records (O(n log n) time, O(n) space) or calling heapify on all n records (O(n) space): When n is tens of millions of trades on disk and k = 10, buffering every record wastes gigabytes of RAM compared to an O(k) streaming min-heap.
  • Using heapq.nlargest(k, trades, key=lambda t: t.notional) without a tie-breaker: On equal scores, Python's nlargest keeps 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 on 15:00:00 gets 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 evicts X at 100 in favor of Y (120) and forgets X's earlier 100, missing X's true winning total of 150.
  • 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_entity for all u entities (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 the score_by_entity dictionary with a balanced search tree or skip list ordered by (-score, entity_key) for O(log u) updates and O(k) reads, or keep only the dictionary on writes (O(1)) and run the size-10 heap across score_by_entity on 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 logs 14:30:00 for 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

Similar questions

More Citadel Securities interview questions

All 4 Citadel Securities questions →