Arrival-Ordered Market Quote Store

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a batch command runner for an arrival-ordered ticker quote store that retains only the newest (bid, ask) pair for each active symbol:

def run_quote_container(operations: List[List]) -> List:

Process operations sequentially and produce a result list with one entry per command:

  • ["push", symbol, bid, ask]:
    • When symbol is not currently active in the store, place it at the back of the arrival queue with quote (bid, ask).
    • When symbol is already active, overwrite its stored bid and ask in place without moving its arrival position.
    • Append None to the output list.
  • ["pop"]:
    • Remove the earliest-arrived active symbol and append [symbol, bid, ask] carrying its most recent prices, or append None when the store holds zero symbols.
    • Once removed by pop, a later valid push for that symbol counts as a fresh arrival at the back.
  • ["size"]:
    • Append the current count of active symbols in the store.
  • Invalid or unknown commands:
    • Any command record that does not match one of the three exact shapes and argument types above must leave the store completely unchanged and append the string "ValueError" to the output list (do not raise an exception).

Every valid command must execute in expected O(1) time.

Examples

Example 1

  • Input: python operations = [ ["push", "NVDA", 120, 122], ["push", "AMD", 155, 157], ["push", "NVDA", 124, 125], ["size"], ["pop"], ["push", "NVDA", 130, 131], ["pop"], ["pop"], ["pop"], ]
  • Output: python [None, None, None, 2, ["NVDA", 124, 125], None, ["AMD", 155, 157], ["NVDA", 130, 131], None]
  • Explanation: "NVDA" arrives before "AMD". Updating "NVDA" to (124, 125) keeps "NVDA" ahead of "AMD", so the first pop returns ["NVDA", 124, 125]. Pushing "NVDA" again after it was popped appends it behind "AMD", so subsequent pops return "AMD", then "NVDA", and finally None when empty.

Example 2

  • Input: python operations = [ ["push", "SPY", 510, 511], ["push", "", 10, 11], ["push", "SPY", True, 512], ["peek"], ["size"], ["pop"], ]
  • Output: python [None, "ValueError", "ValueError", "ValueError", 1, ["SPY", 510, 511]]
  • Explanation: Empty ticker strings, boolean values passed as prices, and unrecognized command names each append "ValueError" without altering "SPY"'s stored quote (510, 511).

Constraints

  • Up to 200,000 distinct symbols may be active simultaneously.
  • Valid symbol values are non-empty, case-sensitive str instances ("nvda" and "NVDA" are separate tickers).
  • Valid bid and ask values are exact Python int values (booleans True and False are invalid; negative, zero, large, and bid > ask integers are allowed).
  • Valid records are sequence objects matching the exact arities 4 ("push"), 1 ("pop"), or 1 ("size").

Step-by-step walkthrough

  1. Understand the operations and strict validation rules

    We process a list of market-quote commands and return one output item per command:

    • ["push", symbol, bid, ask]: store (bid, ask) for symbol and append None to the output. If symbol is not currently stored, it takes the newest spot at the back of the line; if symbol is already stored, its bid and ask are replaced without changing its place in line.
    • ["pop"]: remove the oldest remaining symbol and append [symbol, bid, ask] with its most recent prices, or None if the container is empty. (If that symbol is pushed again after being popped, it counts as a brand-new arrival at the back.)
    • ["size"]: append the current count of stored symbols.
    • Any malformed or unknown command: append the literal string "ValueError" (do not raise an exception!) and leave the container untouched.

    Strict shape validation has three details worth catching right away:

    1. push requires exact length 4, while pop and size require exact length 1 (["pop", 1] or ["PUSH", "NVDA", 1, 2] are invalid).
    2. symbol must be a non-empty str ("" is invalid, and "nvda" vs "NVDA" are distinct symbols).
    3. bid and ask must be integers (zero, negative, and bid > ask are valid integers), excluding booleans: in Python bool is a subclass of int, so isinstance(True, int) evaluates to True unless we explicitly reject bool!
  2. Why a single list is too slow

    The simplest brute-force design stores [symbol, bid, ask] rows in a single Python list:

    • push linearly scans rows to check whether symbol is already present (O(n) time).
    • pop calls rows.pop(0), which shifts all n - 1 remaining elements one slot left in memory (O(n) time).

    With up to 200,000 distinct symbols, repeated O(n) scans and shifts take on the order of 200,000^2 = 4 * 10^10 steps — seconds or minutes instead of milliseconds. Every valid command needs expected O(1) time.

  3. Key idea: pair a FIFO deque with a hash map

    Notice where a symbol's position in line can ever change:

    • A brand-new symbol enters at the back.
    • An update to an existing symbol never moves its position.
    • pop removes from the front.

    Nothing is ever deleted from or moved out of the middle! That means the arrival order behaves like a plain FIFO (first-in, first-out) queue (collections.deque), while a dictionary (dict) gives expected O(1) lookup and price replacement by symbol:

    arrival_queue (deque: oldest -> newest)     latest_quotes (dict: symbol -> (bid, ask))
    ---------------------------------------     ------------------------------------------
    1) push NVDA 120 122: ["NVDA"]              {"NVDA": (120, 122)}
    2) push AMD  155 157: ["NVDA", "AMD"]       {"NVDA": (120, 122), "AMD": (155, 157)}
    3) push NVDA 124 125: ["NVDA", "AMD"]       {"NVDA": (124, 125), "AMD": (155, 157)}  <-- order unchanged!
    4) pop:               ["AMD"]               {"AMD": (155, 157)}  --> returns ["NVDA", 124, 125]
    

    Both structures stay perfectly synchronized because of one invariant (a condition that holds before and after every operation): arrival_queue contains the exact keys of latest_quotes, each once, from oldest to newest.

    • push appends symbol to arrival_queue only when symbol not in latest_quotes, then sets latest_quotes[symbol] = (bid, ask).
    • pop pops oldest_symbol from the left of arrival_queue and pops oldest_symbol out of latest_quotes (so if oldest_symbol arrives again later, symbol not in latest_quotes is True again and it joins the back).
  4. Validate each record before touching state

    Checking the whole record inside is_valid(record) before calling container.push(...) guarantees that a half-valid command like ["push", "SPY", True, 512] never partially mutates "SPY".

    def is_integer(value: Any) -> bool:
        # In Python, bool is a subclass of int (isinstance(True, int) == True),
        # so we must explicitly reject True and False as invalid prices.
        return isinstance(value, int) and not isinstance(value, bool)
    
    
    def is_valid(record: Any) -> bool:
        """Return True iff record matches one of the three exact operation shapes."""
        if not isinstance(record, (list, tuple)) or len(record) == 0:
            return False
    
        op_name = record[0]
        if op_name == "push":
            if len(record) != 4:
                return False
            symbol, bid, ask = record[1], record[2], record[3]
            return (
                isinstance(symbol, str)
                and len(symbol) > 0
                and is_integer(bid)
                and is_integer(ask)
            )
    
        if op_name == "pop" or op_name == "size":
            return len(record) == 1
    
        return False
    
  5. Code QuoteContainer and the operation runner

    Every method on QuoteContainer does a constant number of deque endpoint and dict hash operations — expected O(1) time per operation.

    class QuoteContainer:
        """Insertion-ordered quote store with expected O(1) push, pop, and size."""
    
        def __init__(self):
            # latest_quotes: {symbol: (bid, ask)}, e.g. {"NVDA": (124, 125), "AMD": (155, 157)}
            self.latest_quotes: Dict[str, Tuple[int, int]] = {}
            # arrival_queue: FIFO deque of live symbols, oldest on the left, e.g. deque(["NVDA", "AMD"])
            # Invariant: arrival_queue holds the exact keys of latest_quotes, each once, in arrival order.
            self.arrival_queue: deque = deque()
    
        def push(self, symbol: str, bid: int, ask: int) -> None:
            # Only a symbol not currently in the container joins the back of the line;
            # updating an existing symbol overwrites its quote without moving its position.
            if symbol not in self.latest_quotes:
                self.arrival_queue.append(symbol)
            self.latest_quotes[symbol] = (bid, ask)
    
        def pop(self) -> Optional[List]:
            if not self.arrival_queue:
                return None
            # Remove the oldest symbol from BOTH structures so a future push is treated as new.
            oldest_symbol = self.arrival_queue.popleft()
            bid, ask = self.latest_quotes.pop(oldest_symbol)
            return [oldest_symbol, bid, ask]
    
        def size(self) -> int:
            return len(self.latest_quotes)
    
    
    def run_quote_container(operations: List[List]) -> List:
        container = QuoteContainer()
        results: List[Any] = []
    
        for record in operations:
            # Phase 1: Validate the entire record BEFORE mutating state so malformed commands leave state untouched.
            if not is_valid(record):
                results.append("ValueError")
                continue
    
            # Phase 2: Dispatch the verified operation in expected O(1) time.
            op_name = record[0]
            if op_name == "push":
                container.push(record[1], record[2], record[3])
                results.append(None)
            elif op_name == "pop":
                results.append(container.pop())
            else:
                results.append(container.size())
    
        return results
    
  6. Walk through Example 1

    Operation                  | arrival_queue   | latest_quotes                       | Result
    ---------------------------+-----------------+-------------------------------------+--------------------
    ["push", "NVDA", 120, 122] | ["NVDA"]        | {"NVDA": (120,122)}                 | None
    ["push", "AMD",  155, 157] | ["NVDA","AMD"]  | {"NVDA": (120,122), "AMD": (155,157)}| None
    ["push", "NVDA", 124, 125] | ["NVDA","AMD"]  | "NVDA" -> (124,125) (stays 1st!)    | None
    ["size"]                   | ["NVDA","AMD"]  | (2 entries)                         | 2
    ["pop"]                    | ["AMD"]         | "NVDA" removed                      | ["NVDA", 124, 125]
    ["push", "NVDA", 130, 131] | ["AMD","NVDA"]  | + "NVDA": (130,131) (joins back!)   | None
    ["pop"]                    | ["NVDA"]        | "AMD" removed                       | ["AMD", 155, 157]
    ["pop"]                    | []              | "NVDA" removed                      | ["NVDA", 130, 131]
    ["pop"]                    | []              | {}                                  | None
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    class QuoteContainer:
        """Insertion-ordered quote store with expected O(1) push, pop, and size."""
    
        def __init__(self):
            # latest_quotes: {symbol: (bid, ask)}, e.g. {"NVDA": (124, 125), "AMD": (155, 157)}
            self.latest_quotes: Dict[str, Tuple[int, int]] = {}
            # arrival_queue: FIFO deque of live symbols, oldest on the left, e.g. deque(["NVDA", "AMD"])
            # Invariant: arrival_queue holds the exact keys of latest_quotes, each once, in arrival order.
            self.arrival_queue: deque = deque()
    
        def push(self, symbol: str, bid: int, ask: int) -> None:
            # Only a symbol not currently in the container joins the back of the line;
            # updating an existing symbol overwrites its quote without moving its position.
            if symbol not in self.latest_quotes:
                self.arrival_queue.append(symbol)
            self.latest_quotes[symbol] = (bid, ask)
    
        def pop(self) -> Optional[List]:
            if not self.arrival_queue:
                return None
            # Remove the oldest symbol from BOTH structures so a future push is treated as new.
            oldest_symbol = self.arrival_queue.popleft()
            bid, ask = self.latest_quotes.pop(oldest_symbol)
            return [oldest_symbol, bid, ask]
    
        def size(self) -> int:
            return len(self.latest_quotes)
    
    
    def is_integer(value: Any) -> bool:
        # In Python, bool is a subclass of int (isinstance(True, int) == True),
        # so we must explicitly reject True and False as invalid prices.
        return isinstance(value, int) and not isinstance(value, bool)
    
    
    def is_valid(record: Any) -> bool:
        """Return True iff record matches one of the three exact operation shapes."""
        if not isinstance(record, (list, tuple)) or len(record) == 0:
            return False
    
        op_name = record[0]
        if op_name == "push":
            if len(record) != 4:
                return False
            symbol, bid, ask = record[1], record[2], record[3]
            return (
                isinstance(symbol, str)
                and len(symbol) > 0
                and is_integer(bid)
                and is_integer(ask)
            )
    
        if op_name == "pop" or op_name == "size":
            return len(record) == 1
    
        return False
    
    
    def run_quote_container(operations: List[List]) -> List:
        container = QuoteContainer()
        results: List[Any] = []
    
        for record in operations:
            # Phase 1: Validate the entire record BEFORE mutating state so malformed commands leave state untouched.
            if not is_valid(record):
                results.append("ValueError")
                continue
    
            # Phase 2: Dispatch the verified operation in expected O(1) time.
            op_name = record[0]
            if op_name == "push":
                container.push(record[1], record[2], record[3])
                results.append(None)
            elif op_name == "pop":
                results.append(container.pop())
            else:
                results.append(container.size())
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a deli counter with a paper ticket dispenser (arrival_queue) and a wall chalkboard (latest_quotes). When "NVDA" sends a quote for the first time, it takes a ticket at the back of the FIFO (first-in, first-out) queue (collections.deque, where items enter on the right and leave from the left in O(1) time) and writes its (bid, ask) price next to "NVDA" on the chalkboard (dict). If "NVDA" sends an updated quote while still waiting in line, we simply erase and rewrite "NVDA"'s numbers on the chalkboard in O(1) time without touching its ticket in line; when "pop" calls the front ticket, we pull "NVDA" from the front of the queue and erase its latest price from the chalkboard together.

A naive single list of [symbol, bid, ask] entries is far too slow at 200,000 symbols because every push must scan the list in O(n) time to check whether the symbol already exists, and every list.pop(0) shifts all remaining elements left in O(n) time. Even trying to use a plain Python dict alone via oldest = next(iter(d)) followed by del d[oldest] secretly hits O(n^2) time in CPython: deleting keys from the front leaves blank "tombstone" slots at the beginning of the dictionary's internal array that every subsequent next(iter(d)) must scan past until a resize compacts the table!

Trace the first half of Example 1 step by step: 1. ["push", "NVDA", 120, 122]: new symbol -> arrival_queue = ["NVDA"], latest_quotes = {"NVDA": (120, 122)}, output None. 2. ["push", "AMD", 155, 157]: new symbol -> arrival_queue = ["NVDA", "AMD"], latest_quotes adds "AMD": (155, 157), output None. 3. ["push", "NVDA", 124, 125]: already in latest_quotes -> arrival_queue stays ["NVDA", "AMD"], latest_quotes["NVDA"] becomes (124, 125), output None. 4. ["pop"]: popleft() yields "NVDA", latest_quotes.pop("NVDA") yields (124, 125) -> output ["NVDA", 124, 125].

Complexity

Let m be the total number of operation records and n the maximum number of live symbols stored at one time (n <= 200,000), treating each ticker string's short length as O(1).

  • Time — expected O(1) per operation, O(m) overall: Shape validation checks at most 4 fields in O(1) time; deque.append, deque.popleft, and len are worst-case O(1); and dict lookup, assignment, and pop are expected O(1) via hashing.
  • Space — O(n) for the container (plus O(m) for the output list): Each currently stored symbol appears once in arrival_queue and once in latest_quotes, so memory grows linearly with active distinct symbols rather than historical updates.

Edge cases

  • Empty container (pop and size): pop returns None and size returns 0 without raising an error.
  • Repeated updates to the oldest symbol: Updating "NVDA" ten times keeps "NVDA" at the very front of arrival_queue and returns the 10th (bid, ask) on pop.
  • Re-pushing a symbol after it was popped: Because pop deletes the symbol from latest_quotes too, a subsequent push sees symbol not in latest_quotes and appends it to the back of arrival_queue.
  • Boolean values passed as prices (True / False): Rejected as "ValueError" because is_integer explicitly filters out bool (isinstance(True, int) is True in Python).
  • Malformed push for an already-present symbol: Rejected before mutating latest_quotes or arrival_queue, so the symbol's previous quote and queue position remain intact.
  • Case sensitivity and unusual integer prices: "nvda" and "NVDA" are distinct symbols; negative, zero, huge (10^15), and crossed (bid > ask) integers are all accepted because only shape and types are restricted.

Common mistakes

  • Using next(iter(quotes)) + del quotes[k] on a plain Python dict: Looks O(1) at first glance, but consecutive front deletions without insertions scan past 1, 2, ..., n deleted slots in CPython's entry table, turning n pops into O(n^2) time!
  • Deleting and re-inserting on update: Moves an updated symbol to the newest position instead of preserving its original arrival position.
  • Forgetting to remove popped symbols from latest_quotes: Leaves stale keys in the dictionary, causing size() to stay too high and causing a later push of that symbol to skip arrival_queue.append(symbol).
  • Accepting bool via isinstance(x, int): Lets ["push", "SPY", True, 512] pass validation as (1, 512).
  • Raising ValueError instead of appending "ValueError": Aborts the batch runner instead of recording "ValueError" and continuing to the next command.

Alternative approaches

  • collections.OrderedDict: Unlike a plain dict, Python's OrderedDict maintains an internal doubly linked list (a chain of nodes where each node stores pointers to both its previous and next neighbor) alongside its hash table. Overwriting od[symbol] = (bid, ask) preserves position in O(1), and od.popitem(last=False) unlinks the oldest node in true O(1) time. Writing out dict + deque explicitly is usually clearer in interviews because it proves you understand the underlying mechanics without relying on library internals.
  • Custom hash map + doubly linked list: In languages like C++ (std::list + std::unordered_map) or Java (LinkedHashMap), storing pointers to doubly-linked-list nodes gives expected O(1) middle removal as well, which becomes essential if updates must reorder symbols or cancellations are added.

Follow-up questions

  • How would the data structures change if updating a live ticker also moved it to the newest position at the back? A deque can no longer support O(1) updates because pulling a symbol out of the middle of a deque takes O(n) time. Replace deque with a doubly linked list whose nodes are indexed by symbol -> node in the hash map (or use OrderedDict.move_to_end(symbol) in Python), which unlinks the node from its old spot and re-attaches it at the tail in O(1) pointer updates.
  • How could you support an expected O(1) ["cancel", symbol] command that deletes an arbitrary ticker before it reaches the front? With a hash map + doubly linked list, look up node = nodes.pop(symbol) and splice node.prev to node.next in O(1) worst-case time. Alternatively, keep the simpler deque using lazy deletion — marking an item deleted in the map now and cleaning up its stale queue entry later when it reaches the front: assign a monotonically increasing seq integer to each new arrival, store latest_quotes[symbol] = (bid, ask, seq) and arrival_queue.append((symbol, seq)), delete latest_quotes.pop(symbol, None) on cancel, and have pop() loop past any (sym, s) whose (sym, s) no longer matches latest_quotes, running in amortized O(1) time (average O(1) per operation because every queued tuple is skipped at most once).
  • If several market-data feed threads push updates concurrently, how would you keep the container consistent with minimal latency? Because latest_quotes and arrival_queue must stay in sync, locking only one of them creates race conditions; wrap push, pop, and size in a single mutex (threading.Lock, a mutual-exclusion lock allowing one thread inside the critical section at a time), which stays fast under moderate load because every critical section is O(1) memory work. In ultra-low-latency trading systems, avoid lock contention altogether with a single-writer actor design: feed handlers push raw quote events onto lock-free single-producer/single-consumer ring buffers, and one pinned consumer thread owns the QuoteContainer exclusively with zero locking.

Follow-up questions

Similar questions

More Chicago Trading Company interview questions

All 8 Chicago Trading Company questions →