Versioned Lookup Store with Inclusive Range Event Tally
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate a batch of commands on a per-key timestamped value history and an event log, using binary search for point-in-time lookups and inclusive range counts.
You are asked to simulate a small system that holds two independent time-aware components, driven by a list of commands.
Components
1. Versioned store. Every key keeps a history of values, each stamped with the time at which it was written.
set(key, value, timestamp)writesvalueforkeyattimestamp. Ifkeyalready has a value written at exactly thattimestamp, the new value replaces the old one. Writes may arrive in any timestamp order.get(key, timestamp)returns the value ofkeywith the greatest write time that is less than or equal totimestamp. If the key was never written, or every write to it happened aftertimestamp, return the empty string"".
2. Event tally. A single global log of event times, shared by all commands (not per key).
record(timestamp)adds one event attimestamp. Several events may share the same timestamp, and each one is counted separately. Events may arrive in any order.count(start, end)returns how many recorded events have a timestamptwithstart <= t <= end. Both ends are inclusive. Ifstart > end, the answer is0.
The store and the tally do not affect each other.
Task
Implement a function that receives two parallel lists:
operations: command names, each one of"set","get","record","count".arguments: for the command at the same index, its argument list:"set"->[key, value, timestamp]"get"->[key, timestamp]"record"->[timestamp]"count"->[start, end]
Process the commands in order and return a list of the same length as operations. For set and record the entry is None; for get it is the string found; for count it is the integer count. Queries only see commands that appear earlier in the list.
Constraints
operationsandargumentshave the same length.- Keys and values are strings; timestamps and range bounds are integers.
- Timestamps need not be increasing, and may repeat.
- Only the four command names above appear.
- Aim for logarithmic-time lookups per query (plus the cost of keeping data ordered), rather than scanning all history for every query.
Examples
Example 1
Input: run_time_commands(['set', 'set', 'get', 'get', 'get'], [['color', 'red', 1], ['color', 'blue', 4], ['color', 3], ['color', 4], ['color', 0]])
Output: [None, None, 'red', 'blue', '']
Example 2
Input: run_time_commands(['record', 'record', 'record', 'count', 'count'], [[2], [2], [5], [2, 5], [3, 4]])
Output: [None, None, None, 3, 0]
Hints
Hint 1
For each key, keep its (timestamp, value) pairs ordered by timestamp, so a lookup can binary search instead of scanning.
Hint 2
For get, you want the last entry whose timestamp is <= the query time. Find the insertion point to the right of the query time and step back by one; if that index is negative, return an empty string.
Hint 3
Keep the event timestamps in one sorted list. An inclusive count is the number of items <= end minus the number of items < start, and you should return 0 when start > end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two structures.
Versioned store. A dictionary maps each key to a list of (timestamp, value) pairs kept sorted by timestamp.
- On
set, binary search for the timestamp. If a pair with that exact timestamp exists, overwrite its value; otherwise insert the new pair at the found position so the list stays sorted. - On
get, binary search for the rightmost pair whose timestamp is<=the query time. Pairing the timestamp with the largest possible character as a sentinel makesbisect_rightland just past every pair with that timestamp, so stepping back one index gives the answer. If the index is negative (or the key is unknown), return"".
Event tally. A single sorted list of timestamps.
- On
record, insert withinsort, so duplicates stay as separate entries. - On
count(start, end), the number of events in[start, end]isbisect_right(events, end) - bisect_left(events, start). Ifstart > end, return0.
Why it is correct
Both lists are always sorted, so binary search correctly identifies boundaries. The "greatest timestamp not exceeding the query" is exactly the element just before the right insertion point. The inclusive window count is the number of elements <= end minus the number of elements < start, which matches the inclusive semantics, and duplicates are counted because each is its own list entry.
Complexity
- Search steps are
O(log n)per operation. Inserting into a Python list shifts elements, sosetandrecordareO(n)in the worst case for out-of-order arrivals (cheap in practice, andO(1)shifting when timestamps arrive in increasing order).getandcountareO(log n). - Space is
O(n)fornstored writes and events.
Reference solution
from bisect import bisect_left, bisect_right, insort
from typing import List, Optional
def run_time_commands(operations: List[str], arguments: List[List]) -> List[Optional[object]]:
# Each key maps to a list of (timestamp, value) pairs sorted by timestamp.
# A later write at the same timestamp replaces the earlier one.
versions = {}
events = [] # sorted event timestamps; duplicates count separately
results = []
for operation, args in zip(operations, arguments):
if operation == "set":
key, value, timestamp = args
history = versions.setdefault(key, [])
i = bisect_left(history, (timestamp, ""))
if i < len(history) and history[i][0] == timestamp:
history[i] = (timestamp, value)
else:
history.insert(i, (timestamp, value))
results.append(None)
elif operation == "get":
key, timestamp = args
history = versions.get(key, [])
i = bisect_right(history, (timestamp, chr(0x10ffff))) - 1
results.append(history[i][1] if i >= 0 else "")
elif operation == "record":
(timestamp,) = args
insort(events, timestamp)
results.append(None)
elif operation == "count":
start, end = args
if start <= end:
results.append(bisect_right(events, end) - bisect_left(events, start))
else:
results.append(0)
else:
raise ValueError(f"Unknown operation: {operation}")
return results