Coding questions · Chicago Trading Company
Build an Ordered Latest-Quote Container
Build an insertion-ordered container that stores only the latest quote for each stock symbol. Support expected O(1) push, pop, and size operations while updating bid and ask values without changing a symbol's original position and safely rejecting malformed commands.
Implement a top-level operation runner for incoming stock quotes. At most one quote per symbol may be present.
def run_quote_container(operations: list[list]) -> list:
...
Operations are encoded as:
["push", symbol, bid, ask]: insert or update a quote and appendNoneto results.["pop"]: remove the oldest remaining symbol and append its latest[symbol, bid, ask], or appendNonewhen empty.["size"]: append the current number of symbols.
Malformed or unknown operations append the string "ValueError" and leave state unchanged. The first valid push of a symbol establishes its position in insertion order. A later valid push for that symbol replaces its bid and ask without changing that position. Every valid operation must run in expected O(1) time.
Example
Input operations:
[
["push", "AAPL", 95, 97],
["push", "GOOG", 500, 540],
["push", "MSFT", 30, 34],
["push", "GOOG", 501, 520],
["push", "AAPL", 94, 98],
["size"], ["pop"],
["push", "MSFT", 32, 35],
["pop"], ["pop"], ["pop"]
]
Output:
[
None, None, None, None, None,
3, ["AAPL", 94, 98], None,
["GOOG", 501, 520], ["MSFT", 32, 35], None
]
Constraints
- Symbols are nonempty case-sensitive strings.
- Bid and ask are integers.
- The container may hold up to
200_000distinct symbols. - Operation records must have exactly the shapes defined above.
Clarifications
- This practice version follows the example: updating a symbol does not make it newest in the ordering.
- After a symbol is popped, a later push of that symbol is a new first arrival and appends it to the back.
Hints
- One requirement concerns order; another requires direct access by symbol.
- Choose representations that let a replacement update the exact ordered element without scanning.
Build an Ordered Latest-Quote Container
Maintain at most one latest quote per symbol while retaining each symbol's first-arrival order. Push inserts or replaces without moving an existing symbol; pop removes the oldest symbol; size reports the count. Malformed operations append the literal string ValueError and leave state unchanged.
Hints
- An ordered dictionary supports direct replacement and oldest-item removal.
- After a symbol is popped, a later push is a fresh arrival at the back.
Approach
OrderedDict preserves first insertion order while assignment replaces the current quote in place. popitem(last=False) removes the oldest remaining symbol in constant expected time.
- Time complexity: O(number of operations) expected
- Space complexity: O(number of distinct resident symbols)