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") accepts granularity equal to "day" or "hour"; any other value raises ValueError.
  • Ticker symbols: Every symbol must be a str containing at least one non-whitespace character; empty, blank, or non-string tickers raise ValueError.
  • Decimal prices: Convert numeric or string prices via Decimal(str(value)). Prices must be finite (not NaN, not Infinity), >= 0, and not bool instances; invalid prices raise ValueError.
  • Timestamps (naive exchange-local wall-clock times; timezone-aware datetime objects raise ValueError):
    • "day" mode: Accepts "YYYY-MM-DD" strings, datetime.date objects, or naive datetime.datetime objects 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 naive datetime.datetime objects aligned to an exact hour (minute == second == microsecond == 0). Bare date objects (that are not datetime) are rejected with ValueError.
  • Initial loading: Exact duplicate initial records whose Decimal values are equal (such as "25.0" and 25) merge silently, whereas two records for the same (symbol, timestamp) with different prices raise ValueError. Initial loading does not count as an update.

Required Operations

  • absolute_change(start_price: Decimal, end_price: Decimal) -> Decimal: Returns end_price - start_price.
  • get_price(symbol, timestamp) -> Optional[Decimal]: Validates symbol and timestamp, returning the stored Decimal quote or None when the ticker or slot has no recorded quote.
  • get_change(symbol, start, end, formula=absolute_change) -> Optional[object]: Validates symbol, start, and end (raising ValueError when start > end). If either endpoint has no stored quote, return None. Otherwise return formula(start_price, end_price), catching (ArithmeticError, ValueError) raised inside formula (for example, division by a zero start price) and returning None.
  • update_prices(symbol, start, end, new_prices) -> bool: Steps across every consecutive slot (1 day or 1 hour per step) in the inclusive interval [start, end], where new_prices[i] corresponds to start + i * step.
    • Raise ValueError (modifying nothing) if symbol or timestamps are malformed, start > end, len(new_prices) does not equal the exact number of slots in [start, end], or any element of new_prices is invalid.
    • Return False (modifying nothing) if symbol was never loaded or if any slot in [start, end] for symbol was already written by an earlier update_prices call.
    • Otherwise atomically write every slot in [start, end] (populating previously missing gap slots as well), mark all of those slots as updated, and return True.
  • get_hourly_prices(symbol, day) -> List[Tuple[datetime, Decimal]]: Supported only when granularity == "hour" (raises ValueError on a daily store). Parses day at daily granularity ("YYYY-MM-DD", date, or midnight datetime) and returns (timestamp, price) pairs from 00:00 through 23:00 of 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, and get_hourly_prices across 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 formula callbacks.

Step-by-step walkthrough

  1. 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"): Passing granularity="day" (the default) or granularity="hour" to StockPriceStore controls both timestamp validation and whether update_prices steps by 1 day or 1 hour.
    • Exact decimal prices: Never store financial quotes as binary float (0.1 + 0.2 is 0.30000000000000004). We convert every price with Decimal(str(value)) and require it to be finite and >= 0.
    • Timestamps in naive exchange-local time: Daily mode accepts "YYYY-MM-DD", date, or midnight datetime. Hourly mode accepts "YYYY-MM-DD HH:MM" or "YYYY-MM-DDTHH:MM" (optional :SS) or datetime on an exact hour (minute == second == microsecond == 0), and rejects a bare date because guessing 00:00 would silently return the wrong hour.
    • Malformed inputs vs missing data: Caller mistakes—bad date strings, start > end, negative/NaN prices, empty symbols, or passing the wrong number of prices—raise ValueError. Legitimate missing data returns None (get_price, get_change), [] (get_hourly_prices), or False (update_prices).
    • Initial duplicates vs updates: Identical initial records ("10.0" and 10) merge cleanly; conflicting prices for the same (symbol, timestamp) raise ValueError. Initial loading does not count as an update—only update_prices marks slots as updated.
  2. 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 storing date in daily mode and datetime in hourly mode? In Python, datetime is a subclass of date, yet date(2025, 5, 2) == datetime(2025, 5, 2, 0, 0) evaluates to False! Using datetime keys everywhere avoids subtle key-type mismatches.

    And what about get_hourly_prices ordered by time? A calendar day has only 24 hours (00:00 through 23: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.

  3. Parse timestamps and prices cleanly at the boundary

    Funneling all inputs through three small boundary helpers (validate_symbol, parse_timestamp, and to_price) means the core store methods only ever touch clean str, datetime, and Decimal values.

    Watch out for three classic Python edge cases here: 1. isinstance(value, datetime) before isinstance(value, date): Because datetime inherits from date, testing date first would catch datetime(2025, 6, 10, 9, 30) and silently throw away its 09:30 time! 2. bool subclasses int: Reject isinstance(value, bool) in to_price so True is never accepted as price 1. 3. Decimal("NaN") < 0 raises InvalidOperation: Check not price.is_finite() before price < 0 so short-circuit or catches NaN and Infinity cleanly.

    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 price
    
  4. Load initial records and detect conflicting duplicates

    In __init__, we validate granularity, initialize self._prices, self._updated, and self._lock, and feed every initial record through _load.

    Because Decimal("10.0") == Decimal("10") is True, harmless formatting differences ("10.0" vs 10) are treated as identical duplicates and merged, whereas genuinely different prices (10 vs 11) raise ValueError instead 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] = value
    
  5. Read prices and run custom change formulas safely

    get_price validates the symbol and timestamp, then reads self._prices under self._lock so it never observes a half-finished batch update from another thread.

    get_change fetches both start_price and end_price under one lock acquisition (so both come from a consistent snapshot). If either price is missing, we return None. Otherwise we call formula(start_price, end_price) outside self._lock for two reasons: 1. A slow or blocking caller callback cannot freeze other threads using the store. 2. Domain math failures—such as dividing by a 0 start price in a percentage-change formula (DivisionByZero, a subclass of ArithmeticError) or math.log(0) (ValueError)—are caught and returned as None. Programming bugs like TypeError are 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 None
    
  6. Guarantee 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 returns False).

    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 start and end, compute slot_count = (end_ts - start_ts) // self._step + 1 with integer division, verify len(new_prices) == slot_count, convert every price with to_price, and build the slots list. If anything raises ValueError, we haven't touched the store. 2. Phase 2 (Check and apply inside one with self._lock: block): Verify symbol exists and check every (symbol, ts) against self._updated before 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 True
    
  7. Query hourly prices for a calendar day in 24 lookups

    When granularity == "hour", every existing method already works at hourly granularity (_step is timedelta(hours=1), so update_prices from 09:00 to 11:00 expects 3 prices).

    To implement get_hourly_prices(symbol, day): 1. Reject calls on a daily store with ValueError. 2. Parse day using "day" granularity (day_start is YYYY-MM-DD 00:00:00). 3. Under self._lock, loop hour from 0 to 23 and check day_start + timedelta(hours=hour) in series. Any recorded hours come back in ascending chronological order, and 24:00 (the next day's 00: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 result
    
  8. Trace Example 1 and assemble the complete solution

    Let's trace Example 1 on a daily store initialized with NVDA = 114.50 on 2025-05-02 and 119.00 on 2025-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 False
    

    Here 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 the n initial 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, then timestamp).
  • get_change: O(1) average time plus the runtime of formula, doing two O(1) dictionary lookups under the lock and invoking formula(start_price, end_price) once outside the lock.
  • update_prices: O(k) average time (and O(1) rejection when len(new_prices) disagrees with the arithmetically computed slot count), because we validate k prices, perform at most k set-membership checks in self._updated, and write k dictionary and set entries.
  • get_hourly_prices: O(1) time, because a calendar day always has at most 24 hourly timestamps (00:00 to 23:00). Probing those 24 keys directly in chronological order does 24 constant-time hash lookups regardless of n and avoids sorting altogether.
  • Space: O(n + u) in memory, storing one Decimal per populated (symbol, timestamp) slot in self._prices and one (symbol, timestamp) tuple per updated slot in self._updated.

Edge cases

  • Weekends, market holidays, and missing hours: Missing slots are normal in financial data; get_price and get_change return None rather than inventing or forward-filling values, while update_prices fills missing slots inside its range and marks them updated.
  • Unknown symbol vs malformed symbol: An unknown ticker like "ORCL" returns None, [], or False, whereas an empty, whitespace-only, or non-string ticker ("", " ", None) raises ValueError.
  • Single-slot range (start == end): get_change evaluates formula(p, p) (Decimal("0") for absolute_change), and update_prices updates that single slot when len(new_prices) == 1.
  • Inverted range (start > end): Raises ValueError in both get_change and update_prices because 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; 10 and 11 on the same key raise ValueError.
  • Zero start price in custom formulas: Percentage change (end - start) / start * 100 raises decimal.DivisionByZero when start == 0; get_change catches (ArithmeticError, ValueError) and returns None.
  • 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:00 in autumn and skips 02:00 in spring, store UTC timestamps internally and convert timezones at the API boundary.

Common mistakes

  • Storing prices as float or calling Decimal(0.1) directly: Decimal(0.1) copies the binary float inaccuracy of 0.1; always convert through Decimal(str(value)) and reject bool, NaN, Infinity, and negatives.
  • Checking isinstance(x, date) before isinstance(x, datetime): Because datetime is a subclass of date, checking date first silently strips the hour and minute off every datetime argument.
  • 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's update_prices write loop can observe new prices on Monday and stale prices on Tuesday in get_change or get_hourly_prices.
  • Holding self._lock while calling formula: formula is 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 before t" 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 answer get_price_as_of(symbol, t), run binary search (i = bisect_right(timestamps, t) - 1) to find the largest recorded timestamp <= t in O(log n) time, returning None if i < 0 (meaning t precedes the stock's very first record). Whenever update_prices fills 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_prices in a single database transaction (a group of SQL statements that commit together or roll back together) backed by a price_updates(symbol, ts, PRIMARY KEY (symbol, ts)) table. First INSERT all k (symbol, ts) rows into price_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) the k prices into prices and 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 _updated with an append-only version list per (symbol, timestamp): [(version, price, updated_at, actor, reason), ...], where version 0 is the initial load. get_price reads versions[-1].price in O(1), policy rules (such as "at most one unapproved correction" or "no edits after market close + 24h") inspect versions inside the lock, and auditors can query get_price_at_version(symbol, timestamp, version) to reconstruct any historical snapshot.

Follow-up questions

Similar questions

More Lead Bank interview questions

All 8 Lead Bank questions →