Time-Aware Key-Field Store with Expiration
Data Structure DesignAuto-graded · 28 test casesLast updated
Tests ability to implement an in-memory store with nested key-field structure, lexicographic scanning, timestamps, and TTL-based expiration logic.
Build an in-memory storage system that organizes data by keys and fields, supports time-based operations, and handles automatic expiration.
The store manages records indexed by string key. Each record contains multiple fields, where both field names and their value are strings.
Your implementation must process a sequence of operations and return their results.
Operations
Basic Operations
set(key, field, value): Storevalueunder the givenfieldin the record identified bykey. Create the record if it doesn't exist yet. Returnnull.get(key, field): Retrieve the current value offieldin the record. Returnnullif the record or field doesn't exist.delete(key, field): Removefieldfrom the record. Returntrueif the field existed and was removed,falseotherwise. Records with no remaining fields may be removed from the store.
Retrieval Operations
scan(key): Return all fields in the record as a list, sorted alphabetically by field name. Each entry should be formatted as"field(value)". Return an empty list if the record doesn't exist.scan_by_prefix(key, prefix): Return all fields whose names begin withprefix, sorted alphabetically and formatted as"field(value)". Return an empty list if no fields match.
Time-Based Operations
Fields can be written with a specific timestamp and optional expiration time.
set_at(key, field, value, timestamp): Storevalueat the giventimestampwithout expiration. Returnnull.set_at_with_ttl(key, field, value, timestamp, ttl): Storevalueattimestampwith a time-to-live ofttl. The field is visible for queries at timetwheretimestamp <= t < timestamp + ttl. Returnnull.get_at(key, field, timestamp): Retrieve the value visible attimestamp. Returnnullif no valid value exists at that time.delete_at(key, field, timestamp): Removefieldif it exists and is visible attimestamp. Returntrueif deleted,falseotherwise.scan_at(key, timestamp): Return all fields visible attimestamp, sorted and formatted as inscan.scan_by_prefix_at(key, prefix, timestamp): Return all fields visible attimestampwhose names start withprefix, sorted and formatted as inscan_by_prefix.
Behavior Rules
- Timestamps in time-based operations are guaranteed to be non-decreasing.
- A later write to the same
(key, field)pair completely replaces the previous value and its expiration policy. - Fields that have expired or been deleted must not appear in any retrieval operations.
- A field written with
set_at_with_ttlexpires at exactlytimestamp + ttl(not visible at or after this time). - Empty prefix
""matches all field names.
Input Format
You will receive two parallel lists:
operations: list of operation names (strings)arguments: list of argument lists, one per operation
Return a list containing one result per operation, in order. Mutations that don't return a value should produce None in the results.
Constraints
- 1 ≤ number of operations ≤ 10,000
- All keys, fields, and values are non-empty strings
- All timestamps and TTL values are non-negative integers
- Timestamps are non-decreasing across operations
Examples
Example 1
Input: time_aware_store(['set', 'get', 'delete', 'get'], [['user1', 'name', 'Alice'], ['user1', 'name'], ['user1', 'name'], ['user1', 'name']])
Output: [None, 'Alice', True, None]
Example 2
Input: time_aware_store(['set', 'set', 'set', 'scan', 'scan_by_prefix', 'get'], [['user1', 'name', 'Alice'], ['user1', 'age', '30'], ['user1', 'nickname', 'Al'], ['user1'], ['user1', 'na'], ['user1', 'age']])
Output: [None, None, None, ['age(30)', 'name(Alice)', 'nickname(Al)'], ['name(Alice)'], '30']
Example 3
Input: time_aware_store(['set_at_with_ttl', 'get_at', 'get_at', 'scan_at'], [['k', 'f', 'v', 10, 5], ['k', 'f', 12], ['k', 'f', 15], ['k', 14]])
Output: [None, 'v', None, ['f(v)']]
Example 4
Input: time_aware_store(['set_at', 'set_at_with_ttl', 'get_at', 'get_at', 'delete_at', 'get_at'], [['k', 'f', 'old', 1], ['k', 'f', 'new', 5, 3], ['k', 'f', 6], ['k', 'f', 8], ['k', 'f', 8], ['k', 'f', 9]])
Output: [None, None, 'new', None, False, None]
Hints
Hint 1
Use nested dictionaries to map keys to fields, and store both value and expiration information for each field.
Hint 2
For TTL tracking, store when each field expires rather than when it was created. Check expiration at query time rather than actively removing expired entries.
Hint 3
A single helper function can handle all scan operations by accepting a timestamp and optional prefix, filtering by visibility and prefix match, then sorting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires implementing a two-level storage structure with time-based expiration. The core insight is choosing the right data model to make all operations straightforward.
Use nested dictionaries to represent the store structure:
store[key][field] = (value, expiration_time)
Each field stores a tuple containing its value and when it expires. For fields without expiration (from set or set_at), store None as the expiration time.
For fields with TTL (from set_at_with_ttl), calculate and store the absolute expiration time as timestamp + ttl.
A single visibility check handles all expiration logic:
is_visible(entry, t) = entry exists AND (expiration is None OR t < expiration)
This check enforces the half-open interval [timestamp, timestamp + ttl) specified in the problem.
Implementation Details
Write operations (set* variants) create or overwrite the tuple. When you write to the same field again, both the value and expiration policy are replaced completely.
Read operations (get* variants) look up the entry and check visibility at the query timestamp.
Delete operations remove the field if it exists and passes the visibility check. When deleting the last field from a record, remove the entire key from the store.
Scan operations share a common helper function that:
- Retrieves all fields for the key
- Filters by prefix match (empty prefix matches everything)
- Filters by visibility at the query timestamp
- Sorts field names alphabetically
- Formats each as
"field(value)"
For non-timestamped operations (scan, scan_by_prefix), use infinity as the timestamp so that permanent fields are visible but TTL-based fields are always considered expired.
Why This Works
The half-open interval [timestamp, timestamp + ttl) means a field expires exactly at timestamp + ttl, so checking t < expiration_time correctly excludes expired fields.
Since timestamps are non-decreasing, we never query before a field was written, so we only need to store the expiration time, not the creation time.
Expired entries remain in the store but are filtered at read time (lazy expiration). This is simpler than eager cleanup and produces identical results since every read path applies the visibility check.
Complexity
Let F = number of fields in a record, P = prefix length, N = total operations.
Time:
- Write operations (
set*,delete*): O(1) average per operation - Point queries (
get*): O(1) average per operation - Scan operations: O(F log F + F·P) per scan for sorting and prefix matching
Space: O(total fields stored, including expired but not yet removed entries)
Overall time complexity is O(N·F log F) worst case if every operation is a scan.
from typing import List
def time_aware_store(operations: List[str], arguments: List[List]) -> List:
store = {}
results = []
def is_visible(entry, timestamp):
if entry is None:
return False
value, expiration_time = entry
return expiration_time is None or timestamp < expiration_time
def retrieve_fields(key, timestamp, prefix=''):
record = store.get(key, {})
return [
f'{field}({record[field][0]})'
for field in sorted(record)
if field.startswith(prefix) and is_visible(record[field], timestamp)
]
for operation, args in zip(operations, arguments):
if operation == 'set':
key, field, value = args
store.setdefault(key, {})[field] = (value, None)
results.append(None)
elif operation == 'get':
key, field = args
entry = store.get(key, {}).get(field)
results.append(entry[0] if entry is not None else None)
elif operation == 'delete':
key, field = args
record = store.get(key, {})
existed = field in record
if existed:
del record[field]
if not record:
store.pop(key, None)
results.append(existed)
elif operation == 'scan':
key = args[0]
results.append(retrieve_fields(key, float('inf')))
elif operation == 'scan_by_prefix':
key, prefix = args
results.append(retrieve_fields(key, float('inf'), prefix))
elif operation == 'set_at':
key, field, value, timestamp = args
store.setdefault(key, {})[field] = (value, None)
results.append(None)
elif operation == 'set_at_with_ttl':
key, field, value, timestamp, ttl = args
store.setdefault(key, {})[field] = (value, timestamp + ttl)
results.append(None)
elif operation == 'get_at':
key, field, timestamp = args
entry = store.get(key, {}).get(field)
results.append(entry[0] if is_visible(entry, timestamp) else None)
elif operation == 'delete_at':
key, field, timestamp = args
record = store.get(key, {})
entry = record.get(field)
existed = is_visible(entry, timestamp)
if existed:
del record[field]
if not record:
store.pop(key, None)
results.append(existed)
elif operation == 'scan_at':
key, timestamp = args
results.append(retrieve_fields(key, timestamp))
elif operation == 'scan_by_prefix_at':
key, prefix, timestamp = args
results.append(retrieve_fields(key, timestamp, prefix))
else:
raise ValueError(f'Unknown operation: {operation}')
return results