Time-Series Stock Quote Store
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build a thread-safe in-memory time-series quote store StockPriceStore (along with the default change helper absolute_change) that ingests (symbol, timestamp, price) tuples at either daily or hourly resolution and supports point lookups, custom price-change calculations, write-once atomic range updates, and single-day hourly scans.
Data Model & Validation Rules
- Granularity:
StockPriceStore(records, granularity="day")acceptsgranularityequal to"day"or"hour"; any other value raisesValueError. - Ticker symbols: Every
symbolmust be astrcontaining at least one non-whitespace character; empty, blank, or non-string tickers raiseValueError. - Decimal prices: Convert numeric or string prices via
Decimal(str(value)). Prices must be finite (not NaN,not Infinity),>= 0, and notboolinstances; invalid prices raiseValueError. - Timestamps (naive exchange-local wall-clock times; timezone-aware
datetimeobjects raiseValueError):"day"mode: Accepts"YYYY-MM-DD"strings,datetime.dateobjects, or naivedatetime.datetimeobjects aligned to midnight (00:00:00.000000)."hour"mode: Accepts"YYYY-MM-DD HH:MM","YYYY-MM-DDTHH:MM","YYYY-MM-DD HH:MM:SS", or"YYYY-MM-DDTHH:MM:SS"strings, or naivedatetime.datetimeobjects aligned to an exact hour (minute == second == microsecond == 0). Baredateobjects (that are notdatetime) are rejected withValueError.
- Initial loading: Exact duplicate initial records whose
Decimalvalues are equal (such as"25.0"and25) merge silently, whereas two records for the same(symbol, timestamp)with different prices raiseValueError. Initial loading does not count as an update.
Required Operations
absolute_change(start_price: Decimal, end_price: Decimal) -> Decimal: Returnsend_price - start_price.get_price(symbol, timestamp) -> Optional[Decimal]: Validatessymbolandtimestamp, returning the storedDecimalquote orNonewhen the ticker or slot has no recorded quote.get_change(symbol, start, end, formula=absolute_change) -> Optional[object]: Validatessymbol,start, andend(raisingValueErrorwhenstart > end). If either endpoint has no stored quote, returnNone. Otherwise returnformula(start_price, end_price), catching(ArithmeticError, ValueError)raised insideformula(for example, division by a zero start price) and returningNone.update_prices(symbol, start, end, new_prices) -> bool: Steps across every consecutive slot (1 dayor1 hourper step) in the inclusive interval[start, end], wherenew_prices[i]corresponds tostart + i * step.- Raise
ValueError(modifying nothing) ifsymbolor timestamps are malformed,start > end,len(new_prices)does not equal the exact number of slots in[start, end], or any element ofnew_pricesis invalid. - Return
False(modifying nothing) ifsymbolwas never loaded or if any slot in[start, end]forsymbolwas already written by an earlierupdate_pricescall. - Otherwise atomically write every slot in
[start, end](populating previously missing gap slots as well), mark all of those slots as updated, and returnTrue.
- Raise
get_hourly_prices(symbol, day) -> List[Tuple[datetime, Decimal]]: Supported only whengranularity == "hour"(raisesValueErroron a daily store). Parsesdayat daily granularity ("YYYY-MM-DD",date, or midnightdatetime) and returns(timestamp, price)pairs from00:00through23:00of that calendar day in ascending chronological order, or[]if none exist.
Examples
Example 1
store = StockPriceStore([
("NVDA", "2025-05-02", "114.50"),
("NVDA", "2025-05-05", "119.00"),
])
store.get_price("NVDA", "2025-05-02") # Decimal("114.50")
store.get_price("NVDA", "2025-05-03") # None
store.get_change("NVDA", "2025-05-02", "2025-05-05") # Decimal("4.50")
store.update_prices("NVDA", "2025-05-02", "2025-05-03", ["115.00", "116.25"]) # True
store.update_prices("NVDA", "2025-05-03", "2025-05-04", ["120.00", "121.00"]) # False
store.get_price("NVDA", "2025-05-04") # None
Walk-through: May 3 has no initial quote (None), while get_change from May 2 to May 5 computes 119.00 - 114.50 = Decimal("4.50"). The first update_prices updates May 2, fills the May 3 gap, and marks both dates updated (True). The second update_prices overlaps on May 3, so it aborts atomically (False) and leaves May 3 at 116.25 and May 4 at None.
Example 2
hourly = StockPriceStore(
[
("SHOP", "2025-06-10 14:00", "82.40"),
("SHOP", "2025-06-10 09:00", "80.10"),
("SHOP", "2025-06-11 00:00", "83.00"),
],
granularity="hour",
)
hourly.get_hourly_prices("SHOP", "2025-06-10")
# Output:
# [
# (datetime(2025, 6, 10, 9, 0), Decimal("80.10")),
# (datetime(2025, 6, 10, 14, 0), Decimal("82.40")),
# ]
Walk-through: get_hourly_prices returns the two quotes recorded on 2025-06-10 ordered from earliest hour to latest hour, excluding 2025-06-11 00:00.
Constraints
- Concurrent calls to
get_price,get_change,update_prices, andget_hourly_pricesacross multiple threads must be thread-safe: overlapping writers on the same slots must never both succeed, and readers must never observe partially applied batch updates. - Do not hold internal locks while executing user-supplied
formulacallbacks.
Step-by-step walkthrough
Pin down the API contract and error rules
Before writing any storage code, let's establish a clear, consistent boundary contract across all operations:
- Granularity (
"day"or"hour"): Passinggranularity="day"(the default) orgranularity="hour"toStockPriceStorecontrols both timestamp validation and whetherupdate_pricessteps by 1 day or 1 hour. - Exact decimal prices: Never store financial quotes as binary
float(0.1 + 0.2is0.30000000000000004). We convert every price withDecimal(str(value))and require it to be finite and>= 0. - Timestamps in naive exchange-local time: Daily mode accepts
"YYYY-MM-DD",date, or midnightdatetime. Hourly mode accepts"YYYY-MM-DD HH:MM"or"YYYY-MM-DDTHH:MM"(optional:SS) ordatetimeon an exact hour (minute == second == microsecond == 0), and rejects a baredatebecause guessing00:00would silently return the wrong hour. - Malformed inputs vs missing data: Caller mistakes—bad date strings,
start > end, negative/NaNprices, empty symbols, or passing the wrong number of prices—raiseValueError. Legitimate missing data returnsNone(get_price,get_change),[](get_hourly_prices), orFalse(update_prices). - Initial duplicates vs updates: Identical initial records (
"10.0"and10) merge cleanly; conflicting prices for the same(symbol, timestamp)raiseValueError. Initial loading does not count as an update—onlyupdate_pricesmarks slots as updated.
- Granularity (
Design the in-memory layout for O(1) lookups
Every operation accesses quotes at exact day or hour slots, so nested hash tables plus a set of updated slots give us O(1) average lookup time without sorting:
StockPriceStore (granularity = "day", _step = 1 day) ├── _prices: Dict[str, Dict[datetime, Decimal]] │ "NVDA" ──> { 2025-05-02 00:00: Decimal("114.50"), │ 2025-05-05 00:00: Decimal("119.00") } │ ├── _updated: Set[Tuple[str, datetime]] │ { ("NVDA", 2025-05-02 00:00), ("NVDA", 2025-05-03 00:00) } │ └── _lock: threading.Lock() (guards _prices and _updated together)Why normalize daily keys to midnight
datetime(Y, M, D, 0, 0)instead of storingdatein daily mode anddatetimein hourly mode? In Python,datetimeis a subclass ofdate, yetdate(2025, 5, 2) == datetime(2025, 5, 2, 0, 0)evaluates toFalse! Usingdatetimekeys everywhere avoids subtle key-type mismatches.And what about
get_hourly_pricesordered by time? A calendar day has only 24 hours (00:00through23:00). Probing those 24 timestamps in order takes 24 O(1) dictionary lookups regardless of whether the store holds 100 or 10,000,000 records, and produces sorted output automatically.Parse timestamps and prices cleanly at the boundary
Funneling all inputs through three small boundary helpers (
validate_symbol,parse_timestamp, andto_price) means the core store methods only ever touch cleanstr,datetime, andDecimalvalues.Watch out for three classic Python edge cases here: 1.
isinstance(value, datetime)beforeisinstance(value, date): Becausedatetimeinherits fromdate, testingdatefirst would catchdatetime(2025, 6, 10, 9, 30)and silently throw away its09:30time! 2.boolsubclassesint: Rejectisinstance(value, bool)into_pricesoTrueis never accepted as price1. 3.Decimal("NaN") < 0raisesInvalidOperation: Checknot price.is_finite()beforeprice < 0so short-circuitorcatchesNaNandInfinitycleanly.from typing import List from datetime import date, datetime, timedelta from decimal import Decimal, InvalidOperation DAY_FORMATS = ["%Y-%m-%d"] HOUR_FORMATS = [ "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", ] STEPS = {"day": timedelta(days=1), "hour": timedelta(hours=1)} def validate_symbol(symbol: object) -> str: """Require a non-empty ticker string; raise ValueError for malformed symbols.""" if not isinstance(symbol, str) or symbol.strip() == "": raise ValueError(f"bad symbol {symbol!r}") return symbol def _parse_text(text: str, formats: List[str]) -> datetime: for fmt in formats: try: return datetime.strptime(text, fmt) except ValueError: pass raise ValueError(f"cannot parse {text!r}; expected one of {formats}") def parse_timestamp(value: object, granularity: str) -> datetime: """Return a naive datetime aligned to a day or hour boundary, else raise ValueError.""" # Check datetime BEFORE date because datetime is a subclass of date in Python. if isinstance(value, datetime): ts = value elif isinstance(value, date): if granularity == "hour": raise ValueError(f"{value!r} has no hour") ts = datetime(value.year, value.month, value.day) elif isinstance(value, str): formats = DAY_FORMATS if granularity == "day" else HOUR_FORMATS ts = _parse_text(value.strip(), formats) else: raise ValueError(f"unsupported timestamp {value!r}") if ts.tzinfo is not None: raise ValueError("use naive timestamps in exchange local time") on_hour = ts.minute == 0 and ts.second == 0 and ts.microsecond == 0 if not on_hour or (granularity == "day" and ts.hour != 0): raise ValueError(f"{value!r} is not on a {granularity} boundary") return ts def to_price(value: object) -> Decimal: """Convert value to a finite, non-negative Decimal; raise ValueError otherwise.""" if isinstance(value, bool): raise ValueError(f"not a price: {value!r}") try: price = Decimal(str(value)) except InvalidOperation: raise ValueError(f"not a price: {value!r}") if not price.is_finite() or price < 0: raise ValueError(f"price must be finite and >= 0: {value!r}") return priceLoad initial records and detect conflicting duplicates
In
__init__, we validategranularity, initializeself._prices,self._updated, andself._lock, and feed every initial record through_load.Because
Decimal("10.0") == Decimal("10")isTrue, harmless formatting differences ("10.0"vs10) are treated as identical duplicates and merged, whereas genuinely different prices (10vs11) raiseValueErrorinstead of silently overwriting data.from typing import Dict, Iterable, Set, Tuple import threading from datetime import datetime from decimal import Decimal class StockPriceStore: def __init__(self, records: Iterable[Tuple[str, object, object]], granularity: str = "day") -> None: if granularity not in STEPS: raise ValueError(f"granularity must be 'day' or 'hour', got {granularity!r}") self._granularity = granularity self._step = STEPS[granularity] self._prices: Dict[str, Dict[datetime, Decimal]] = {} self._updated: Set[Tuple[str, datetime]] = set() self._lock = threading.Lock() for symbol, timestamp, price in records: self._load(symbol, timestamp, price) def _load(self, symbol: str, timestamp: object, price: object) -> None: clean_symbol = validate_symbol(symbol) ts = parse_timestamp(timestamp, self._granularity) value = to_price(price) series = self._prices.setdefault(clean_symbol, {}) old = series.get(ts) if old is not None and old != value: raise ValueError(f"conflicting records for {clean_symbol} at {ts}: {old} and {value}") series[ts] = valueRead prices and run custom change formulas safely
get_pricevalidates the symbol and timestamp, then readsself._pricesunderself._lockso it never observes a half-finished batch update from another thread.get_changefetches bothstart_priceandend_priceunder one lock acquisition (so both come from a consistent snapshot). If either price is missing, we returnNone. Otherwise we callformula(start_price, end_price)outsideself._lockfor two reasons: 1. A slow or blocking caller callback cannot freeze other threads using the store. 2. Domain math failures—such as dividing by a0start price in a percentage-change formula (DivisionByZero, a subclass ofArithmeticError) ormath.log(0)(ValueError)—are caught and returned asNone. Programming bugs likeTypeErrorare intentionally not caught so broken caller code surfaces immediately.from typing import Callable, Optional, Tuple from datetime import datetime from decimal import Decimal def absolute_change(start_price: Decimal, end_price: Decimal) -> Decimal: """Default formula for get_change: end_price - start_price.""" return end_price - start_price class StockPriceStore: def _parse(self, timestamp: object) -> datetime: return parse_timestamp(timestamp, self._granularity) def _parse_range(self, start: object, end: object) -> Tuple[datetime, datetime]: start_ts = self._parse(start) end_ts = self._parse(end) if start_ts > end_ts: raise ValueError(f"start {start!r} is after end {end!r}") return start_ts, end_ts def get_price(self, symbol: str, timestamp: object) -> Optional[Decimal]: clean_symbol = validate_symbol(symbol) ts = self._parse(timestamp) with self._lock: return self._prices.get(clean_symbol, {}).get(ts) def get_change( self, symbol: str, start: object, end: object, formula: Callable[[Decimal, Decimal], object] = absolute_change, ) -> Optional[object]: clean_symbol = validate_symbol(symbol) start_ts, end_ts = self._parse_range(start, end) with self._lock: series = self._prices.get(clean_symbol, {}) start_price = series.get(start_ts) end_price = series.get(end_ts) if start_price is None or end_price is None: return None try: return formula(start_price, end_price) except (ArithmeticError, ValueError): return NoneGuarantee all-or-nothing batch updates under concurrency
update_prices(symbol, start, end, new_prices)must be atomic (either every slot in[start, end]updates, or nothing changes at all) and write-once per slot (if any slot in[start, end]was already updated earlier, the entire call fails and returnsFalse).Why do naive implementations fail here?
Bug 1 — Writing as you go: update(day 0..2, [5, 6, -7]) writes day 0 = 5, writes day 1 = 6, hits -7 -> raises ValueError! Result: days 0 and 1 are already overwritten (broken atomicity!). Bug 2 — Checking outside the lock: Thread A checks day 1 not in _updated -> True Thread B checks day 1 not in _updated -> True (interleaved!) Thread A writes [10, 20]; Thread B overwrites [30, 40] -> BOTH return True!We prevent both bugs with a clean two-phase structure: 1. Phase 1 (Validate outside the lock): Parse
startandend, computeslot_count = (end_ts - start_ts) // self._step + 1with integer division, verifylen(new_prices) == slot_count, convert every price withto_price, and build theslotslist. If anything raisesValueError, we haven't touched the store. 2. Phase 2 (Check and apply inside onewith self._lock:block): Verifysymbolexists and check every(symbol, ts)againstself._updatedbefore writing a single slot. Because all inputs were already converted in Phase 1, the write loop cannot raise an exception partway through—no undo/rollback code needed!from typing import List from datetime import datetime from decimal import Decimal class StockPriceStore: def update_prices(self, symbol: str, start: object, end: object, new_prices: List[object]) -> bool: clean_symbol = validate_symbol(symbol) start_ts, end_ts = self._parse_range(start, end) slot_count = (end_ts - start_ts) // self._step + 1 if len(new_prices) != slot_count: raise ValueError(f"expected {slot_count} prices from {start} to {end}, got {len(new_prices)}") converted_prices: List[Decimal] = [] for raw_price in new_prices: converted_prices.append(to_price(raw_price)) slots: List[datetime] = [] for i in range(slot_count): slots.append(start_ts + i * self._step) with self._lock: series = self._prices.get(clean_symbol) if series is None: return False for ts in slots: if (clean_symbol, ts) in self._updated: return False for ts, value in zip(slots, converted_prices): series[ts] = value self._updated.add((clean_symbol, ts)) return TrueQuery hourly prices for a calendar day in 24 lookups
When
granularity == "hour", every existing method already works at hourly granularity (_stepistimedelta(hours=1), soupdate_pricesfrom09:00to11:00expects3prices).To implement
get_hourly_prices(symbol, day): 1. Reject calls on a daily store withValueError. 2. Parsedayusing"day"granularity (day_startisYYYY-MM-DD 00:00:00). 3. Underself._lock, loophourfrom0to23and checkday_start + timedelta(hours=hour)inseries. Any recorded hours come back in ascending chronological order, and24:00(the next day's00:00) is never touched.from typing import List, Tuple from datetime import datetime, timedelta from decimal import Decimal class StockPriceStore: def get_hourly_prices(self, symbol: str, day: object) -> List[Tuple[datetime, Decimal]]: if self._granularity != "hour": raise ValueError("this store holds daily prices") clean_symbol = validate_symbol(symbol) day_start = parse_timestamp(day, "day") result: List[Tuple[datetime, Decimal]] = [] with self._lock: series = self._prices.get(clean_symbol, {}) for hour in range(24): ts = day_start + timedelta(hours=hour) if ts in series: result.append((ts, series[ts])) return resultTrace Example 1 and assemble the complete solution
Let's trace Example 1 on a daily store initialized with
NVDA = 114.50on2025-05-02and119.00on2025-05-05:Initial state: _prices["NVDA"] = {2025-05-02: 114.50, 2025-05-05: 119.00} _updated = set() 1) get_change("NVDA", "2025-05-02", "2025-05-05") -> start_price = 114.50, end_price = 119.00 -> 119.00 - 114.50 = Decimal("4.50") 2) update_prices("NVDA", "2025-05-02", "2025-05-03", ["115.00", "116.25"]) -> 2 slots [May 2, May 3], neither in _updated -> writes both (filling May 3 gap)! -> _prices["NVDA"][May 2] = 115.00, _prices["NVDA"][May 3] = 116.25 -> _updated = {("NVDA", May 2), ("NVDA", May 3)} => returns True 3) update_prices("NVDA", "2025-05-03", "2025-05-04", ["120.00", "121.00"]) -> checks [May 3, May 4]: ("NVDA", May 3) IS in _updated! -> aborts before writing: May 3 stays 116.25, May 4 stays None => returns FalseHere is the complete
solution.py:from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple import threading from datetime import date, datetime, timedelta from decimal import Decimal, InvalidOperation DAY_FORMATS = ["%Y-%m-%d"] HOUR_FORMATS = [ "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", ] STEPS = {"day": timedelta(days=1), "hour": timedelta(hours=1)} def absolute_change(start_price: Decimal, end_price: Decimal) -> Decimal: """Default formula for get_change: end_price - start_price.""" return end_price - start_price def validate_symbol(symbol: object) -> str: """Require a non-empty ticker string; raise ValueError for malformed symbols.""" if not isinstance(symbol, str) or symbol.strip() == "": raise ValueError(f"bad symbol {symbol!r}") return symbol def _parse_text(text: str, formats: List[str]) -> datetime: for fmt in formats: try: return datetime.strptime(text, fmt) except ValueError: pass raise ValueError(f"cannot parse {text!r}; expected one of {formats}") def parse_timestamp(value: object, granularity: str) -> datetime: """Return a naive datetime aligned to a day or hour boundary, else raise ValueError.""" # Check datetime BEFORE date because datetime is a subclass of date in Python. if isinstance(value, datetime): ts = value elif isinstance(value, date): # In an hourly store, a bare date like date(2024, 1, 2) is ambiguous (which hour?). if granularity == "hour": raise ValueError(f"{value!r} has no hour") ts = datetime(value.year, value.month, value.day) elif isinstance(value, str): formats = DAY_FORMATS if granularity == "day" else HOUR_FORMATS ts = _parse_text(value.strip(), formats) else: raise ValueError(f"unsupported timestamp {value!r}") if ts.tzinfo is not None: raise ValueError("use naive timestamps in exchange local time") # Hour mode requires exact ":00:00" boundaries; day mode additionally requires 00:00 midnight. on_hour = ts.minute == 0 and ts.second == 0 and ts.microsecond == 0 if not on_hour or (granularity == "day" and ts.hour != 0): raise ValueError(f"{value!r} is not on a {granularity} boundary") return ts def to_price(value: object) -> Decimal: """Convert value to a finite, non-negative Decimal; raise ValueError otherwise.""" if isinstance(value, bool): raise ValueError(f"not a price: {value!r}") try: # Convert through str() first so float 0.1 becomes Decimal('0.1'), # not Decimal('0.1000000000000000055511151231257827021181583404541015625'). price = Decimal(str(value)) except InvalidOperation: raise ValueError(f"not a price: {value!r}") # Check is_finite() BEFORE price < 0 because comparing Decimal('NaN') < 0 # raises InvalidOperation instead of returning False. if not price.is_finite() or price < 0: raise ValueError(f"price must be finite and >= 0: {value!r}") return price class StockPriceStore: """Thread-safe in-memory store of (symbol, timestamp, price) records.""" def __init__(self, records: Iterable[Tuple[str, object, object]], granularity: str = "day") -> None: if granularity not in STEPS: raise ValueError(f"granularity must be 'day' or 'hour', got {granularity!r}") self._granularity = granularity self._step = STEPS[granularity] # _prices: symbol -> {slot_datetime: Decimal_price}, e.g. {"NVDA": {datetime(2025, 5, 2): Decimal("114.50")}} self._prices: Dict[str, Dict[datetime, Decimal]] = {} # _updated: set of (symbol, slot_datetime) pairs written by update_prices (initial load does not mark slots). self._updated: Set[Tuple[str, datetime]] = set() # _lock: single mutex guarding reads and multi-slot writes across _prices and _updated. self._lock = threading.Lock() for symbol, timestamp, price in records: self._load(symbol, timestamp, price) def _load(self, symbol: str, timestamp: object, price: object) -> None: clean_symbol = validate_symbol(symbol) ts = parse_timestamp(timestamp, self._granularity) value = to_price(price) series = self._prices.setdefault(clean_symbol, {}) old = series.get(ts) # Exact duplicates (e.g. "10.0" and 10) merge cleanly; conflicting prices raise an error. if old is not None and old != value: raise ValueError(f"conflicting records for {clean_symbol} at {ts}: {old} and {value}") series[ts] = value def _parse(self, timestamp: object) -> datetime: return parse_timestamp(timestamp, self._granularity) def _parse_range(self, start: object, end: object) -> Tuple[datetime, datetime]: start_ts = self._parse(start) end_ts = self._parse(end) if start_ts > end_ts: raise ValueError(f"start {start!r} is after end {end!r}") return start_ts, end_ts def get_price(self, symbol: str, timestamp: object) -> Optional[Decimal]: clean_symbol = validate_symbol(symbol) ts = self._parse(timestamp) with self._lock: return self._prices.get(clean_symbol, {}).get(ts) def get_change( self, symbol: str, start: object, end: object, formula: Callable[[Decimal, Decimal], object] = absolute_change, ) -> Optional[object]: clean_symbol = validate_symbol(symbol) start_ts, end_ts = self._parse_range(start, end) with self._lock: series = self._prices.get(clean_symbol, {}) start_price = series.get(start_ts) end_price = series.get(end_ts) if start_price is None or end_price is None: return None # Run the caller-supplied formula outside the lock so a slow callback cannot stall # other threads, and turn domain math errors (e.g. division by zero) into None. try: return formula(start_price, end_price) except (ArithmeticError, ValueError): return None def update_prices(self, symbol: str, start: object, end: object, new_prices: List[object]) -> bool: # Phase 1: Validate symbol, range, slot count, and every price BEFORE acquiring the lock # or mutating state, so bad inputs never leave a half-written update. clean_symbol = validate_symbol(symbol) start_ts, end_ts = self._parse_range(start, end) slot_count = (end_ts - start_ts) // self._step + 1 if len(new_prices) != slot_count: raise ValueError(f"expected {slot_count} prices from {start} to {end}, got {len(new_prices)}") converted_prices: List[Decimal] = [] for raw_price in new_prices: converted_prices.append(to_price(raw_price)) slots: List[datetime] = [] for i in range(slot_count): slots.append(start_ts + i * self._step) # Phase 2: Check "never updated before" and apply all slots inside ONE lock acquisition, # preventing both partial updates and race conditions between overlapping writers. with self._lock: series = self._prices.get(clean_symbol) if series is None: return False for ts in slots: if (clean_symbol, ts) in self._updated: return False for ts, value in zip(slots, converted_prices): series[ts] = value self._updated.add((clean_symbol, ts)) return True def get_hourly_prices(self, symbol: str, day: object) -> List[Tuple[datetime, Decimal]]: if self._granularity != "hour": raise ValueError("this store holds daily prices") clean_symbol = validate_symbol(symbol) day_start = parse_timestamp(day, "day") # Probe the 24 exact hours 00:00..23:00 in chronological order: O(1) lookups, # already sorted, and guaranteed never to include the next day's 00:00. result: List[Tuple[datetime, Decimal]] = [] with self._lock: series = self._prices.get(clean_symbol, {}) for hour in range(24): ts = day_start + timedelta(hours=hour) if ts in series: result.append((ts, series[ts])) return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture StockPriceStore as a financial ledger book with one page per stock ticker (NVDA, SHOP). Each line on a page represents an exact time slot—midnight of a calendar day in daily mode, or an exact top-of-the-hour timestamp in hourly mode—and carries a tamper-evident "corrected" stamp next to the price. Initial loading pencils in the starting quotes without stamping any lines; a batch correction (update_prices) is allowed only if none of the requested lines on that ticker's page have been stamped yet, and stamps every line it touches at the same moment.
Naive implementations stumble in three places. First, storing prices as float introduces binary rounding artifacts (0.1 + 0.2 == 0.30000000000000004). Second, looping through a date range and writing prices as you go breaks atomicity (the all-or-nothing guarantee that either every slot updates or none do) whenever a later slot fails validation or turns out to be stamped already. Third, checking "was any slot updated?" without a mutex (threading.Lock, a lock that lets only one thread enter a protected code block at a time) lets two concurrent threads both pass the check and overwrite each other.
Walk through Example 1's ledger for "NVDA" loaded with (May 2, "114.50") and (May 5, "119.00") (where May 3–4 are a weekend gap):
- get_price("NVDA", "2025-05-02") looks up self._prices["NVDA"][2025-05-02] in O(1) and returns Decimal("114.50"), while "2025-05-03" returns None.
- get_change("NVDA", "2025-05-02", "2025-05-05") reads 114.50 and 119.00 together under the lock, releases the lock, and runs 119.00 - 114.50 = Decimal("4.50").
- update_prices("NVDA", "2025-05-02", "2025-05-03", ["115.00", "116.25"]) validates both prices first, locks the ledger, sees neither date in _updated, writes both (filling the May 3 gap), and stamps both in _updated. A follow-up update_prices("NVDA", "2025-05-03", "2025-05-04", ["120.00", "121.00"]) sees May 3 is already stamped, leaves May 3 and May 4 untouched, and returns False.
Complexity
Let n be the number of initial records loaded, k be the number of time slots in an update_prices range, and u be the total number of slots ever updated.
__init__: O(n) average time, because we parse each of theninitial records once and perform one O(1) average dictionary lookup and insertion per record.get_price: O(1) average time, doing constant-time timestamp parsing followed by two hash-table lookups (symbol, thentimestamp).get_change: O(1) average time plus the runtime offormula, doing two O(1) dictionary lookups under the lock and invokingformula(start_price, end_price)once outside the lock.update_prices: O(k) average time (and O(1) rejection whenlen(new_prices)disagrees with the arithmetically computed slot count), because we validatekprices, perform at mostkset-membership checks inself._updated, and writekdictionary and set entries.get_hourly_prices: O(1) time, because a calendar day always has at most 24 hourly timestamps (00:00to23:00). Probing those 24 keys directly in chronological order does 24 constant-time hash lookups regardless ofnand avoids sorting altogether.- Space: O(n + u) in memory, storing one
Decimalper populated(symbol, timestamp)slot inself._pricesand one(symbol, timestamp)tuple per updated slot inself._updated.
Edge cases
- Weekends, market holidays, and missing hours: Missing slots are normal in financial data;
get_priceandget_changereturnNonerather than inventing or forward-filling values, whileupdate_pricesfills missing slots inside its range and marks them updated. - Unknown symbol vs malformed symbol: An unknown ticker like
"ORCL"returnsNone,[], orFalse, whereas an empty, whitespace-only, or non-string ticker (""," ",None) raisesValueError. - Single-slot range (
start == end):get_changeevaluatesformula(p, p)(Decimal("0")forabsolute_change), andupdate_pricesupdates that single slot whenlen(new_prices) == 1. - Inverted range (
start > end): RaisesValueErrorin bothget_changeandupdate_pricesbecause the caller supplied an invalid interval. - Partial overlap on
update_prices: Overlapping a previously updated range by even one day or one hour rejects the entire batch without modifying the non-overlapping slots; adjacent non-overlapping ranges succeed. - Identical vs conflicting initial duplicates:
("X", "2024-01-02", "10.0")and("X", "2024-01-02", 10)have equal fixed-point decimal (Decimal, base-10 exact arithmetic) values and merge cleanly;10and11on the same key raiseValueError. - Zero start price in custom formulas: Percentage change
(end - start) / start * 100raisesdecimal.DivisionByZerowhenstart == 0;get_changecatches(ArithmeticError, ValueError)and returnsNone. - Daylight saving time: This store uses naive timestamps (wall-clock dates/times without a timezone offset) in exchange-local time, which works cleanly for standard equity market hours. For 24/7 assets (crypto, FX) where DST repeats
01:00in autumn and skips02:00in spring, store UTC timestamps internally and convert timezones at the API boundary.
Common mistakes
- Storing prices as
floator callingDecimal(0.1)directly:Decimal(0.1)copies the binary float inaccuracy of0.1; always convert throughDecimal(str(value))and rejectbool,NaN,Infinity, and negatives. - Checking
isinstance(x, date)beforeisinstance(x, datetime): Becausedatetimeis a subclass ofdate, checkingdatefirst silently strips the hour and minute off everydatetimeargument. - Mutating slots before validating all inputs and slots: Writing slot 0 before discovering slot 2 has price
"-7"or was already updated leaves corrupt half-written state. Always validate everything first, check all slots second, and write third. - Letting readers skip
self._lock: Although a single CPython dictionary lookup does not corrupt memory, a reader running mid-way through another thread'supdate_priceswrite loop can observe new prices on Monday and stale prices on Tuesday inget_changeorget_hourly_prices. - Holding
self._lockwhile callingformula:formulais user-supplied code; running it inside the critical section (the code block executed while holding the lock) lets a slow callback stall all other readers and writers, or deadlock if the callback calls back into the store. - Sorting all timestamps of a symbol for
get_hourly_prices: Filtering and sorting all stored timestamps takes O(n log n) per query when 24 direct hash probes take O(1).
Alternative approaches
- Sorted timestamp arrays with binary search (
bisect): Keeping a sorted list of timestamps per symbol lets you support arbitrary multi-day range scans (get_prices(symbol, start, end)) or "latest price on or beforet" in binary search time—O(log n) by repeatedly halving the sorted search interval—at the cost of O(n) list insertion when filling gaps (or O(log n) with a balanced tree). - Per-symbol locks (
Dict[str, threading.Lock]): Replacing one store-wide lock with one lock per ticker lets concurrent updates to"NVDA"and"SHOP"proceed in parallel without contending on each other.
Follow-up questions
- How would you support an 'as-of' query that returns the latest recorded quote on or before a requested weekend or holiday? Alongside each symbol's
{timestamp: price}dictionary, maintain a sorted list of its timestamps. To answerget_price_as_of(symbol, t), run binary search (i = bisect_right(timestamps, t) - 1) to find the largest recorded timestamp<= tin O(log n) time, returningNoneifi < 0(meaningtprecedes the stock's very first record). Wheneverupdate_pricesfills a previously missing gap slot, insert that new timestamp into the sorted list as well. - If quotes were stored in a shared relational database accessed by multiple application servers, how would you enforce atomic write-once range updates? Wrap
update_pricesin a single database transaction (a group of SQL statements that commit together or roll back together) backed by aprice_updates(symbol, ts, PRIMARY KEY (symbol, ts))table. FirstINSERTallk(symbol, ts)rows intoprice_updates; if any slot was already updated—even concurrently on another server—the primary-key constraint fails one statement, and rolling back the transaction leaves zero changes. Otherwise upsert (INSERT ... ON CONFLICT (symbol, ts) DO UPDATE, inserting missing gap rows and updating existing rows) thekprices intopricesand commit. - How would the data model change if compliance rules permitted multiple price revisions per slot as long as every historical version remained auditable? Replace the boolean membership set
_updatedwith an append-only version list per(symbol, timestamp):[(version, price, updated_at, actor, reason), ...], where version0is the initial load.get_pricereadsversions[-1].pricein O(1), policy rules (such as "at most one unapproved correction" or "no edits after market close + 24h") inspectversionsinside the lock, and auditors can queryget_price_at_version(symbol, timestamp, version)to reconstruct any historical snapshot.
Follow-up questions
- How would you support an 'as-of' query that returns the latest recorded quote on or before a requested weekend or holiday?
- If quotes were stored in a shared relational database accessed by multiple application servers, how would you enforce atomic write-once range updates?
- How would the data model change if compliance rules permitted multiple price revisions per slot as long as every historical version remained auditable?
Similar questions
- Versioned Key-Value Store with Snapshots
- Mutable Ticker Price Ledger
- Dynamic Interval Calendar with Overlap and Page Queries
- Timestamped Key-Value Store and Mutual-Friend Recommendations
- Distributed Hotel Room Search and Booking Architecture
- Room-Level Hotel Booking Without Overlapping Stays
More Lead Bank interview questions
- Room-Level Hotel Booking Without Overlapping Stays Medium
- Dynamic Interval Calendar with Overlap and Page Queries Medium
- Mutable Ticker Price Ledger Medium Pro
- Distributed Hotel Room Search and Booking Architecture Medium Pro
- Balancing PM Deadlines and AI Code Safety in Financial Systems Medium Pro
- Versioned Key-Value Store with Snapshots Medium Pro
- Timestamped Key-Value Store and Mutual-Friend Recommendations Medium Pro