Build an In-Memory Price History Store with One-Shot Updates
Data Structure DesignModel answerLast updated
Design a per-symbol price store supporting lookups, custom change formulas, atomic range updates that can touch each slot only once, and a switch from daily to hourly data.
You are given a batch of historical price records for traded securities. Every record has:
symbol: a ticker stringtimestamp: at first a calendar date (one price per day)price: a decimal number
Build an in-memory class, PriceHistoryStore, built from those records. You choose the exact method signatures and return types, but the behavior must be well defined and easy to test.
Required operations
- Point lookup.
get_price(symbol, date)returns the price of that symbol on that date. If no price exists, return a clear "missing" result (for exampleNone). - Change between two dates.
get_change(symbol, start_date, end_date)returns how the price moved between the two dates. The calculation is a pluggable function such asformula(start_price, end_price), supplied by the caller. Decide what happens if either price is missing or the formula cannot be evaluated (for example, a percentage change from a start price of zero). - One-shot range update.
update_prices(symbol, start_date, end_date, new_prices)overwrites the prices of one symbol across the inclusive date range and returns whether it succeeded.- If any slot in that range has been changed by an earlier successful update, the whole call fails.
- The call is atomic: either every price is written or none is.
- Hourly data. The granularity is now one price per hour instead of per day. Add
get_hourly_prices(symbol, day), which returns every hourly price for that symbol on that calendar day, ordered by time.
What to cover
State and handle the following explicitly:
- duplicate initial records (identical and conflicting)
- unknown symbols and missing dates
- invalid ranges (start after end, or the wrong number of new prices)
- repeated and partially overlapping updates
- failures that would otherwise leave a half-applied update
- parsing of dates and times (strings, date objects, misaligned or timezone-aware values)
Finish with a set of representative test cases for your implementation.
Hints
Hint 1
Keep a separate structure per symbol: a hash map from timestamp to price for O(1) lookups, plus a sorted list of timestamps so a whole day can be sliced out later.
Hint 2
For atomicity, use validate-then-commit: parse every input and run every check that can fail (range, length, overlap with already-updated slots) before writing anything. The write phase then cannot fail midway.
Hint 3
Normalize at the boundary (symbol case and whitespace, timestamps onto the granularity grid, prices as Decimal), so daily and hourly modes differ only in the step size. For hourly queries, two binary searches (day start and next day start) give the slice.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Write the contract first, then pick a small number of structures per symbol.
prices[symbol]:dict[datetime, Decimal], giving O(1) point lookups forget_priceandget_change.times[symbol]: a sorted list of the same timestamps. A day's hourly data is the slice between two binary searches.updated[symbol]: a set of timestamps already changed byupdate_prices, which enforces the "each slot may be updated only once" rule.
Normalize at the boundary
- Symbols: strip whitespace and uppercase, so
" aapl "equals"AAPL". - Timestamps: parse to naive
datetimevalues on the granularity grid. In daily mode the time must be midnight. In hourly mode minutes, seconds and microseconds must be zero. Acceptdate,datetimeand ISO strings; reject timezone-aware values (single-timezone assumption). - Prices: convert with
Decimal(str(x))to avoid binary float noise. Reject negative, NaN and infinite values.
Daily and hourly modes then differ only by the step (timedelta(days=1) vs timedelta(hours=1)), so part 4 does not require rewriting parts 1 to 3.
Contract decisions to state aloud
| Situation | Behavior |
|---|---|
| Duplicate initial record, same price | Deduplicate silently |
| Duplicate initial record, different price | Raise ValueError (ambiguous data) |
| Unknown symbol or missing timestamp in a query | Return None |
| Malformed query input (bad string, misaligned time) | Raise ValueError (caller bug, not missing data) |
| Formula raises (e.g. divide by zero) | Return None |
update_prices rejected for any reason | Return False, no state change |
Start after end, or len(new_prices) differs from slot count | False |
| Any slot was updated before | False for the entire call |
| Update targets a slot with no existing price | Allowed (inserts it); "existing only" is a one-line change |
Why it is correct
Atomicity. update_prices is validate-then-commit. Everything that can fail runs before the first write: parsing every price, checking the range, checking the length, and intersecting the slots with updated. The commit loop performs only dict and list writes on validated data, so the store is either fully updated or untouched.
Repeated updates. updated grows only after a successful commit, so a later call fails exactly when its range intersects a previously committed one, even by a single slot.
Hourly queries. times[symbol] is sorted once at load and maintained with insort on insertion. The slice from bisect_left(day 00:00) to bisect_left(next day 00:00) is exactly that day's prices, already ordered.
Complexity
With n initial records, m timestamps for a symbol, k slots in an update and h results:
- Construction: O(n log n) time, O(n) space.
get_price: O(1).get_change: O(1) plus the formula cost.update_prices: O(k) to validate; O(k) to commit if all slots exist, plus O(m) per newly inserted slot because of the list insert.get_hourly_prices: O(log m + h).
Code
from bisect import bisect_left, insort
from datetime import date, datetime, timedelta
from decimal import Decimal, InvalidOperation
from typing import Callable, Iterable, Optional
Formula = Callable[[Decimal, Decimal], Decimal]
def absolute_change(a: Decimal, b: Decimal) -> Decimal:
return b - a
class PriceHistoryStore:
def __init__(self, records: Iterable[tuple], granularity: str = "daily"):
if granularity not in ("daily", "hourly"):
raise ValueError("granularity must be 'daily' or 'hourly'")
self._hourly = granularity == "hourly"
self._step = timedelta(hours=1) if self._hourly else timedelta(days=1)
self._prices: dict[str, dict[datetime, Decimal]] = {}
self._times: dict[str, list[datetime]] = {}
self._updated: dict[str, set[datetime]] = {}
for sym, ts, price in records:
s, t, p = self._sym(sym), self._ts(ts), self._price(price)
series = self._prices.setdefault(s, {})
if t in series and series[t] != p:
raise ValueError(f"conflicting duplicate for {s} at {t}")
series[t] = p
for s, series in self._prices.items():
self._times[s] = sorted(series)
self._updated[s] = set()
@staticmethod
def _sym(x) -> str:
if not isinstance(x, str) or not x.strip():
raise ValueError("bad symbol")
return x.strip().upper()
def _ts(self, v) -> datetime:
if isinstance(v, datetime):
t = v
elif isinstance(v, date):
t = datetime(v.year, v.month, v.day)
elif isinstance(v, str):
t = datetime.fromisoformat(v.strip())
else:
raise ValueError(f"unsupported timestamp {v!r}")
if t.tzinfo is not None:
raise ValueError("timezone-aware not supported")
if t.minute or t.second or t.microsecond or (not self._hourly and t.hour):
raise ValueError("timestamp not aligned to granularity")
return t
@staticmethod
def _price(v) -> Decimal:
try:
p = Decimal(str(v))
except (InvalidOperation, ValueError):
raise ValueError(f"invalid price {v!r}")
if not p.is_finite() or p < 0:
raise ValueError(f"invalid price {v!r}")
return p
@staticmethod
def _day(v) -> date:
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if isinstance(v, str):
return date.fromisoformat(v.strip())
raise ValueError(f"unsupported day {v!r}")
def get_price(self, symbol, ts) -> Optional[Decimal]:
series = self._prices.get(self._sym(symbol))
t = self._ts(ts)
return None if series is None else series.get(t)
def get_change(self, symbol, start, end,
formula: Formula = absolute_change) -> Optional[Decimal]:
a, b = self.get_price(symbol, start), self.get_price(symbol, end)
if a is None or b is None:
return None
try:
return formula(a, b)
except (ArithmeticError, ValueError):
return None
def update_prices(self, symbol, start, end, new_prices) -> bool:
try:
s, t0, t1 = self._sym(symbol), self._ts(start), self._ts(end)
new = [self._price(p) for p in new_prices]
except ValueError:
return False
if t0 > t1:
return False
slots, t = [], t0
while t <= t1:
slots.append(t)
t += self._step
if len(slots) != len(new):
return False
done = self._updated.get(s, set())
if any(x in done for x in slots):
return False
# commit: nothing below can fail
series = self._prices.setdefault(s, {})
times = self._times.setdefault(s, [])
done = self._updated.setdefault(s, set())
for slot, p in zip(slots, new):
if slot not in series:
insort(times, slot)
series[slot] = p
done.add(slot)
return True
def get_hourly_prices(self, symbol, day) -> list:
s = self._sym(symbol)
times = self._times.get(s)
if not times:
return []
d = self._day(day)
lo = datetime(d.year, d.month, d.day)
i = bisect_left(times, lo)
j = bisect_left(times, lo + timedelta(days=1))
series = self._prices[s]
return [(t, series[t]) for t in times[i:j]]
Test cases
- Lookup hit, unknown symbol, and missing date return the price,
None,None. - Case and whitespace variants of a symbol resolve to the same series.
- Identical duplicate records load; conflicting duplicates raise.
get_changewith a missing endpoint returnsNone; percent change from a zero start returnsNone.- Update over a valid range succeeds and is visible to
get_price. - Same range again returns
False; an overlapping range by one slot returnsFalseand leaves all other slots unchanged (atomicity check). - Wrong length of
new_prices, or start after end, returnsFalsewith no change. start == endupdates one slot.- Hourly mode: a misaligned time such as
10:30is rejected; a day query returns ordered entries; an empty day returns[]; entries inserted by an update appear in the right order.
Common mistakes
- Writing prices while still validating, leaving a half-applied update after a late failure.
- Using floats for prices.
- Treating a malformed input as "missing" instead of surfacing a caller error.
- Scanning every timestamp for the hourly query instead of using binary search.
- Marking slots as updated before the commit completes.