Session Key Manager with Deferred Cleanup
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests building a session-key store with TTL-based lazy eviction using a hash map and min-heap to process a sequence of operations.
You are simulating a session-key store where each key has a time-to-live (TTL). A key is considered expired once the current time is greater than or equal to its expiration timestamp. You process a list of operations sequentially, each paired with a simulated current time.
Implement a function that takes three parallel lists — operations, arguments, and current_times — and returns a list containing the result of each operation.
Operations
"upsert":arguments[i]is[key, ttl]. Register or overwrite the key so that its expiration timestamp equalscurrent_times[i] + ttl. Always pushes a result ofNone(rendered asnull)."get":arguments[i]is[key]. If the key exists in the store and its expiration timestamp is strictly greater than the current time, return the expiration timestamp. Otherwise return-1. If the key exists but has expired, remove it from the store before returning-1(lazy eviction)."count_active":arguments[i]is[]. Return the number of keys currently in the store that have not expired. Before counting, purge every key whose expiration timestamp is less than or equal to the current time.
Expiration boundary rule
A key with expiration timestamp E observed at time T is expired when T >= E. It is still active when T < E. Apply this rule consistently in both "get" and "count_active".
Stale-heap handling
When "upsert" overwrites an existing key, the old heap entry must not corrupt the store. After popping any heap entry (expiration, key), only treat it as the live entry if the store still maps key to that exact expiration value. Otherwise discard the entry and continue.
Constraints
1 <= len(operations) <= 10^5operations[i]is one of"upsert","get","count_active".keyis a non-empty string of lowercase letters and underscores.ttlis a positive integer.current_timesis non-decreasing across the operation list (time never moves backward).- The total number of distinct keys across all operations is at most
10^5.
Examples
Example 1
Input: session_key_ops(['upsert', 'upsert', 'get', 'get', 'count_active'], [['user_a', 10], ['user_b', 5], ['user_b'], ['user_b'], []], [1000, 1000, 1000, 1007, 1007])
Output: [None, None, 1005, -1, 1]
Example 2
Input: session_key_ops(['upsert', 'upsert', 'upsert', 'get', 'get', 'count_active'], [['a', 10], ['b', 5], ['a', 20], ['a'], ['b'], []], [100, 100, 105, 105, 105, 105])
Output: [None, None, None, 125, -1, 1]
Example 3
Input: session_key_ops(['upsert', 'get', 'count_active', 'get', 'count_active'], [['x', 3], ['x'], [], ['x'], []], [10, 13, 13, 14, 14])
Output: [None, -1, 0, -1, 0]
Hints
Hint 1
Use a hash map to store each key's current expiration timestamp for O(1) lookups and updates.
Hint 2
Push every upsert onto a min-heap keyed by expiration; stale entries are filtered out by checking the map when popped.
Hint 3
For count_active, pop all heap entries whose expiration is at or before the current time, deleting matching keys from the map, then return the map size.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is efficiently tracking which keys are still alive while supporting updates that change a key's expiration. Two data structures work together:
-
A hash map (
expirations) mapping each key to its current expiration timestamp. This is the source of truth for lookups and updates, giving O(1) access. -
A min-heap of
(expiration, key)tuples. The heap letscount_activefind expired entries from the top without scanning every key.
When upsert overwrites a key, the old heap entry stays in place and becomes stale. Rather than searching the heap to update it (which would be O(n)), we simply push a new entry. Later, when we pop an entry, we check whether the map still holds that exact expiration for that key. If not, the entry is stale and we skip it.
For get, we only consult the map. If the key's expiration is at or before the current time, we delete it from the map (lazy eviction) and return -1. Otherwise we return the stored expiration.
For count_active, we pop every heap entry whose expiration is at or before the current time. For each popped entry, we delete the key from the map only if the expiration matches the map's current value (confirming it is the live entry, not a stale one). After the purge, the map contains exactly the active keys, so we return its size.
Correctness
The map invariant holds because every upsert writes the new expiration to the map and pushes a matching heap entry. Stale entries can never delete a newer key because the expiration check fails. The purge in count_active removes all expired entries from both structures. The boundary rule T >= E is applied identically in get and in the heap purge loop, so edge cases at exact expiration are consistent.
Complexity
upsert: O(log n) for the heap push, O(1) for the map write.get: O(1) map lookup.count_active: O(k log n) where k is the number of entries popped. Each heap entry is pushed once and popped at most once, so the total work across allcount_activecalls is amortized O(n log n).- Space: O(n) where n is the total number of
upsertcalls (some entries may be stale).
import heapq
def session_key_ops(operations, arguments, current_times):
expirations = {}
heap = []
results = []
for operation, args, now in zip(operations, arguments, current_times):
if operation == "upsert":
key, ttl = args
expiration = now + ttl
expirations[key] = expiration
heapq.heappush(heap, (expiration, key))
results.append(None)
elif operation == "get":
key = args[0]
expiration = expirations.get(key)
if expiration is None or expiration <= now:
if expiration is not None and expiration <= now:
del expirations[key]
results.append(-1)
else:
results.append(expiration)
elif operation == "count_active":
while heap and heap[0][0] <= now:
expiration, key = heapq.heappop(heap)
if expirations.get(key) == expiration:
del expirations[key]
results.append(len(expirations))
else:
raise ValueError("unknown operation")
return results