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
symbolis not currently active in the store, place it at the back of the arrival queue with quote(bid, ask). - When
symbolis already active, overwrite its storedbidandaskin place without moving its arrival position. - Append
Noneto the output list.
- When
["pop"]:- Remove the earliest-arrived active symbol and append
[symbol, bid, ask]carrying its most recent prices, or appendNonewhen the store holds zero symbols. - Once removed by
pop, a later validpushfor that symbol counts as a fresh arrival at the back.
- Remove the earliest-arrived active symbol and append
["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).
- 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
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 firstpopreturns["NVDA", 124, 125]. Pushing"NVDA"again after it was popped appends it behind"AMD", so subsequent pops return"AMD", then"NVDA", and finallyNonewhen 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,000distinct symbols may be active simultaneously. - Valid
symbolvalues are non-empty, case-sensitivestrinstances ("nvda"and"NVDA"are separate tickers). - Valid
bidandaskvalues are exact Pythonintvalues (booleansTrueandFalseare invalid; negative, zero, large, andbid > askintegers are allowed). - Valid records are sequence objects matching the exact arities
4("push"),1("pop"), or1("size").
Step-by-step walkthrough
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)forsymboland appendNoneto the output. Ifsymbolis not currently stored, it takes the newest spot at the back of the line; ifsymbolis already stored, itsbidandaskare replaced without changing its place in line.["pop"]: remove the oldest remaining symbol and append[symbol, bid, ask]with its most recent prices, orNoneif 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:
pushrequires exact length4, whilepopandsizerequire exact length1(["pop", 1]or["PUSH", "NVDA", 1, 2]are invalid).symbolmust be a non-emptystr(""is invalid, and"nvda"vs"NVDA"are distinct symbols).bidandaskmust be integers (zero, negative, andbid > askare valid integers), excluding booleans: in Pythonboolis a subclass ofint, soisinstance(True, int)evaluates toTrueunless we explicitly rejectbool!
Why a single list is too slow
The simplest brute-force design stores
[symbol, bid, ask]rows in a single Pythonlist:pushlinearly scansrowsto check whethersymbolis already present (O(n)time).popcallsrows.pop(0), which shifts alln - 1remaining elements one slot left in memory (O(n)time).
With up to
200,000distinct symbols, repeatedO(n)scans and shifts take on the order of200,000^2 = 4 * 10^10steps — seconds or minutes instead of milliseconds. Every valid command needs expectedO(1)time.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.
popremoves 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 expectedO(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_queuecontains the exact keys oflatest_quotes, each once, from oldest to newest.pushappendssymboltoarrival_queueonly whensymbol not in latest_quotes, then setslatest_quotes[symbol] = (bid, ask).poppopsoldest_symbolfrom the left ofarrival_queueand popsoldest_symbolout oflatest_quotes(so ifoldest_symbolarrives again later,symbol not in latest_quotesisTrueagain and it joins the back).
Validate each record before touching state
Checking the whole record inside
is_valid(record)before callingcontainer.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 FalseCode QuoteContainer and the operation runner
Every method on
QuoteContainerdoes a constant number ofdequeendpoint anddicthash operations — expectedO(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 resultsWalk 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"] | [] | {} | NoneComplete 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 inO(1)time;deque.append,deque.popleft, andlenare worst-caseO(1); anddictlookup, assignment, andpopare expectedO(1)via hashing. - Space —
O(n)for the container (plusO(m)for the output list): Each currently stored symbol appears once inarrival_queueand once inlatest_quotes, so memory grows linearly with active distinct symbols rather than historical updates.
Edge cases
- Empty container (
popandsize):popreturnsNoneandsizereturns0without raising an error. - Repeated updates to the oldest symbol: Updating
"NVDA"ten times keeps"NVDA"at the very front ofarrival_queueand returns the 10th(bid, ask)onpop. - Re-pushing a symbol after it was popped: Because
popdeletes the symbol fromlatest_quotestoo, a subsequentpushseessymbol not in latest_quotesand appends it to the back ofarrival_queue. - Boolean values passed as prices (
True/False): Rejected as"ValueError"becauseis_integerexplicitly filters outbool(isinstance(True, int)isTruein Python). - Malformed push for an already-present symbol: Rejected before mutating
latest_quotesorarrival_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 Pythondict: LooksO(1)at first glance, but consecutive front deletions without insertions scan past1, 2, ..., ndeleted slots in CPython's entry table, turningnpops intoO(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, causingsize()to stay too high and causing a laterpushof that symbol to skiparrival_queue.append(symbol). - Accepting
boolviaisinstance(x, int): Lets["push", "SPY", True, 512]pass validation as(1, 512). - Raising
ValueErrorinstead of appending"ValueError": Aborts the batch runner instead of recording"ValueError"and continuing to the next command.
Alternative approaches
collections.OrderedDict: Unlike a plaindict, Python'sOrderedDictmaintains 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. Overwritingod[symbol] = (bid, ask)preserves position inO(1), andod.popitem(last=False)unlinks the oldest node in trueO(1)time. Writing outdict + dequeexplicitly 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 expectedO(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
dequecan no longer supportO(1)updates because pulling a symbol out of the middle of adequetakesO(n)time. Replacedequewith a doubly linked list whose nodes are indexed bysymbol -> nodein the hash map (or useOrderedDict.move_to_end(symbol)in Python), which unlinks the node from its old spot and re-attaches it at the tail inO(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 upnode = nodes.pop(symbol)and splicenode.prevtonode.nextinO(1)worst-case time. Alternatively, keep the simplerdequeusing 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 increasingseqinteger to each new arrival, storelatest_quotes[symbol] = (bid, ask, seq)andarrival_queue.append((symbol, seq)), deletelatest_quotes.pop(symbol, None)oncancel, and havepop()loop past any(sym, s)whose(sym, s)no longer matcheslatest_quotes, running in amortizedO(1)time (averageO(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_quotesandarrival_queuemust stay in sync, locking only one of them creates race conditions; wrappush,pop, andsizein 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 isO(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 theQuoteContainerexclusively with zero locking.
Follow-up questions
- How would the data structures change if updating a live ticker also moved it to the newest position at the back?
- How could you support an expected O(1) `["cancel", symbol]` command that deletes an arbitrary ticker before it reaches the front?
- If several market-data feed threads push updates concurrently, how would you keep the container consistent with minimal latency?
Similar questions
- O(1) Sliding-Window Moving Average Runner
- Iterative Deep Merge of Dictionaries
- Reflecting on an Engineering Setback and Lasting Habits
- Inline Pre-Trade Risk Engine for Automated Trading
- Custom C++ UniquePtr and Resizable Vector Templates
- Balancing Peer Coaching and Delivery Under Engineering Roadblocks
More Chicago Trading Company interview questions
- O(1) Sliding-Window Moving Average Runner Medium
- Reflecting on an Engineering Setback and Lasting Habits Medium
- Inline Pre-Trade Risk Engine for Automated Trading Medium Pro
- Custom C++ UniquePtr and Resizable Vector Templates Medium Pro
- Iterative Deep Merge of Dictionaries Easy Pro
- Balancing Peer Coaching and Delivery Under Engineering Roadblocks Medium Pro
- 48-Bit Virtual Address Translation Across TLB, Page Tables, and L1D Medium Pro