Tiered Cache with TTL and Priority Fallback
Data Structure DesignAuto-graded · 18 test casesLast updated
Implement a hierarchical key-value cache with expiration times, priority-based lookups, and lazy eviction across multiple storage tiers.
Problem Description
Build a cache system that organizes data into multiple priority tiers. Each tier stores key-value pairs that expire after a designated time. When retrieving data, the system searches tiers in priority order and returns the first valid (non-expired) match.
Implement a function that processes a sequence of operations on this tiered cache structure.
Operations
Your function receives three parameters:
num_tiers: The number of priority tiers (indexed0tonum_tiers - 1, where tier0has highest priority)operations: A list of operation namesarguments: A list of argument lists, one per operation
The operations are:
-
"store":[key, value, tier, expiry_time]- Place an item in the specified tier with an absolute expiration timestamp
- If the key already exists in that tier, replace both its value and expiration time
-
"retrieve":[key, current_time]- Search for the key starting from tier
0upward - Return the value from the lowest-indexed tier where the key exists and has not expired (
expiry_time > current_time) - Remove any expired entries encountered during the search
- Return
Noneif the key is not found or all copies have expired
- Search for the key starting from tier
-
"purge_expired":[current_time]- Remove all entries across all tiers where
expiry_time <= current_time - Return the count of items removed
- Remove all entries across all tiers where
Return a list of results: None for "store" operations, the retrieved value or None for "retrieve", and the removal count for "purge_expired".
Constraints
1 <= num_tiers <= 160 <= tier < num_tiers1 <= len(key) <= 64(alphanumeric characters)0 <= current_time, expiry_time <= 2 × 10^9-2^31 <= value <= 2^31 - 1- Total operations ≤
10^5
Notes
- An item is considered expired when
expiry_time <= current_time(the boundary case counts as expired) - The same key can exist in multiple tiers with different values and expiration times
- Lazy eviction during
retrievemeans those items won't be counted again bypurge_expired
Examples
Example 1
Input: tiered_cache_operations(3, ['store', 'store', 'store', 'retrieve', 'retrieve', 'retrieve', 'purge_expired'], [['bid', 100, 1, 50], ['bid', 105, 0, 30], ['ask', 110, 2, 40], ['bid', 20], ['bid', 35], ['ask', 45], [60]])
Output: [None, None, None, 105, 100, None, 1]
Example 2
Input: tiered_cache_operations(2, ['store', 'store', 'retrieve', 'retrieve'], [['x', -4, 0, 10], ['x', 7, 1, 20], ['x', 10], ['x', 20]])
Output: [None, None, 7, None]
Hints
Hint 1
Each tier can be represented as a hash map storing key to (value, expiration_time) pairs for O(1) lookup
Hint 2
The retrieve operation should check tiers in order from 0 upward and delete expired entries as it encounters them
Hint 3
For purge_expired, iterate through all keys in each tier and collect those that have expired - this is simpler than maintaining a separate data structure
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to maintain each tier as an independent hash map that stores key-to-(value, expiration_time) pairs. This structure enables constant-time access per tier during retrieval and straightforward iteration during expiration cleanup.
Store Operation: Write or overwrite the entry in the designated tier's map. This is O(1).
Retrieve Operation: Scan tiers sequentially from index 0 upward. For each tier, check if the key exists. If found but expired (expiry_time ≤ current_time), delete it and continue searching. Return the value from the first tier where the key is present and valid. This implements priority-based fallback: lower-indexed tiers take precedence, and expired entries are cleaned up lazily as they're encountered. Time complexity is O(T) where T is the number of tiers (bounded by 16).
Purge Operation: Iterate through every tier, collect all keys whose expiration time is at or before the current time, delete them, and accumulate the count. Since items deleted during retrieve won't appear here, we only count what remains. Time complexity is O(T × K) where K is the average number of keys per tier.
The lazy eviction strategy during retrieve means expired items are removed on-demand rather than proactively, reducing overhead when entries are never accessed again before they expire. The purge operation provides a way to reclaim memory for items that haven't been accessed.
Correctness: The ≤ comparison for expiration ensures the boundary case is handled correctly. Each tier is independent, so the same key can exist in multiple tiers without conflict. The sequential scan in retrieve guarantees the highest-priority valid entry is returned.
Complexity:
- Time: O(1) per store, O(T) per retrieve, O(T × K) per purge
- Space: O(T × total_keys_stored)
Solution
from typing import List, Optional
def tiered_cache_operations(num_tiers: int, operations: List[str], arguments: List[List]) -> List[Optional[int]]:
tiers = [{} for _ in range(num_tiers)]
results = []
for operation, args in zip(operations, arguments):
if operation == "store":
key, value, tier, expiry_time = args
tiers[tier][key] = (value, expiry_time)
results.append(None)
elif operation == "retrieve":
key, current_time = args
result = None
for tier in tiers:
entry = tier.get(key)
if entry is not None:
value, expiry_time = entry
if expiry_time <= current_time:
del tier[key]
else:
result = value
break
results.append(result)
elif operation == "purge_expired":
current_time = args[0]
removed = 0
for tier in tiers:
expired_keys = [key for key, (_, expiry_time) in tier.items() if expiry_time <= current_time]
for key in expired_keys:
del tier[key]
removed += len(expired_keys)
results.append(removed)
return results