Key-Value Store with Expiration and Snapshots
Data Structure DesignAuto-graded · 13 test casesLast updated
Design a nested dictionary with field-level expiration times and the ability to capture and restore database snapshots.
Build a two-level key-value storage system that supports field expiration and snapshot management. Each operation receives a timestamp parameter (a non-decreasing integer) representing the current time.
Your task is to process a sequence of operations on this storage system. Implement a function that takes two parallel lists—one containing operation names and another containing their arguments—and returns a list of results.
Operations
The system supports five operations:
set — [timestamp, key, field, value, ttl]
- Stores
valueat the locationkey -> field. - If
ttl > 0, the field becomes inaccessible at timetimestamp + ttlor later. - If
ttl == 0, the field remains accessible indefinitely. - Overwrites any existing value and expiration for that field.
- Returns:
None
get — [timestamp, key, field]
- Retrieves the value stored at
key -> field. - Returns
Noneif the key or field doesn't exist, or if the field has expired (current time is at or past the expiration time). - Returns: the string value or
None
delete — [timestamp, key, field]
- Removes the field at
key -> field. - Returns
Trueonly if the field existed and had not expired at the given timestamp. - Returns:
TrueorFalse
backup — [timestamp]
- Captures the current database state, including only fields that have not expired at
timestamp. - Assigns a unique integer identifier starting from
1and incrementing with each backup. - Returns: the backup identifier (integer)
restore — [timestamp, backup_id]
- Replaces the entire database with the snapshot identified by
backup_id. - Restored fields keep their original absolute expiration times, so a field may be immediately inaccessible if its expiration time is at or before the restore timestamp.
- Returns
Falseifbackup_idis invalid (not previously created). - Returns:
TrueorFalse
Constraints
1 <= timestamp <= 10^9- Timestamps are non-decreasing across all operations
1 <= len(key), len(field), len(value) <= 64- Keys, fields, and values contain only alphanumeric characters and colons
0 <= ttl <= 10^6- At most
20,000total operations - At most
100backup or restore operations
Examples
Example 1
Input: execute_storage_operations(['set', 'get', 'backup', 'set', 'get', 'restore', 'get', 'get'], [[1, 'user:1', 'name', 'Alice', 10], [5, 'user:1', 'name'], [6], [8, 'user:1', 'name', 'Bob', 0], [9, 'user:1', 'name'], [10, 1], [10, 'user:1', 'name'], [11, 'user:1', 'name']])
Output: [None, 'Alice', 1, None, 'Bob', True, 'Alice', None]
Hints
Hint 1
Store expiration as an absolute timestamp (timestamp + ttl) rather than a relative value, making expiration checks simple and consistent across restores.
Hint 2
When creating a backup, filter out expired fields at that moment and make deep copies so future modifications don't affect the snapshot.
Hint 3
During restore, copy the snapshot data into the active storage rather than aliasing it, preserving the snapshot for potential future restores.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires managing a two-level dictionary with time-based expiration and the ability to save and load snapshots of the database state.
The core insight is to store absolute expiration timestamps rather than relative TTLs. When a field is set with ttl > 0, we calculate expiration_time = timestamp + ttl and store that value. When ttl == 0, we store None to indicate the field never expires.
Expiration checking is done lazily—we never actively remove expired entries. Instead, every operation that accesses data (get, delete, backup) checks whether the current timestamp has reached or passed the expiration time. A field is valid if its expiration is None or if current_time < expiration_time.
Snapshots are created by filtering the storage to include only currently valid fields, then making a deep copy of the remaining data. Deep copying is essential because it prevents future modifications to the live storage from corrupting saved snapshots.
Restoration works by replacing the entire storage with a deep copy of the requested snapshot. We copy from the snapshot rather than aliasing it, ensuring the snapshot remains intact for potential future restores. Restored fields retain their original absolute expiration times, so a field that expired before the restore timestamp will immediately fail validity checks.
Why It Works
- Overwriting fields: A new
setoperation always creates a fresh entry with a new value and expiration, correctly handling both TTL updates and clearing previous expirations. - Delete semantics: Returns
Trueonly when a valid (non-expired) field is removed, matching the specification. - Snapshot isolation: Deep copies ensure that modifications after a backup don't affect the saved state, and modifications after a restore don't corrupt the snapshot.
- Expiration across restore: Since we store absolute expiration times, a field set at time 1 with TTL 10 expires at time 11, regardless of when or how many times we restore snapshots containing it.
Complexity
-
Time complexity:
set,get,delete: O(1) average case for hash table operationsbackup: O(N) where N is the total number of stored fieldsrestore: O(M) where M is the number of fields in the snapshot
-
Space complexity: O(N + S) where N is the number of currently stored fields and S is the total size of all snapshots. In the worst case with 100 backups of 20,000 fields each, this is manageable.
from typing import List
def execute_storage_operations(operations: List[str], arguments: List[List]) -> List:
storage = {} # key -> {field: [value, expiration_time or None]}
snapshots = {} # snapshot_id -> captured storage state
next_snapshot_id = 1
outputs = []
def is_valid(entry, current_time):
"""Check if a field entry is still valid at the given time."""
return entry[1] is None or current_time < entry[1]
for op, args in zip(operations, arguments):
if op == "set":
current_time, key, field, value, ttl = args
field_dict = storage.setdefault(key, {})
expiration = current_time + ttl if ttl > 0 else None
field_dict[field] = [value, expiration]
outputs.append(None)
elif op == "get":
current_time, key, field = args
entry = storage.get(key, {}).get(field)
if entry is None or not is_valid(entry, current_time):
outputs.append(None)
else:
outputs.append(entry[0])
elif op == "delete":
current_time, key, field = args
field_dict = storage.get(key)
entry = field_dict.get(field) if field_dict is not None else None
if entry is None or not is_valid(entry, current_time):
outputs.append(False)
else:
del field_dict[field]
if not field_dict:
del storage[key]
outputs.append(True)
elif op == "backup":
current_time = args[0]
captured = {}
for key, field_dict in storage.items():
valid_fields = {
field: [entry[0], entry[1]]
for field, entry in field_dict.items()
if is_valid(entry, current_time)
}
if valid_fields:
captured[key] = valid_fields
snapshots[next_snapshot_id] = captured
outputs.append(next_snapshot_id)
next_snapshot_id += 1
elif op == "restore":
current_time, snapshot_id = args
if snapshot_id not in snapshots:
outputs.append(False)
else:
storage = {
key: {
field: [entry[0], entry[1]]
for field, entry in field_dict.items()
}
for key, field_dict in snapshots[snapshot_id].items()
}
outputs.append(True)
return outputs