TTL-Aware LRU Cache with Lazy Expiration
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests ability to design an O(1) key-value store combining LRU eviction with per-entry time-to-live expiration using a hash map and doubly linked list.
TTL-Aware LRU Cache with Lazy Expiration
Build a fixed-capacity in-memory store where every entry carries its own expiration deadline. The store evicts the least recently used entry when it runs out of room, and treats any entry whose deadline has passed as if it never existed.
Interface
Your implementation must support the following sequence of operations, dispatched by a driver function described below:
put(key, value, ttl, now) → None
get(key, now) → int
put(key, value, ttl, now)
Stores key with the given value. The entry becomes expired at time now + ttl (i.e., it is valid while the current time is strictly less than now + ttl, and expired once the current time reaches or exceeds now + ttl).
- If
keyalready exists and has not yet expired: overwrite its value, reset its deadline tonow + ttl, and mark it as the most recently used entry. The total number of stored entries does not change, so no eviction occurs. - If
keyalready exists but has expired: discard the stale entry completely and treat this as a brand-new insertion. - After inserting a fresh entry, if the number of stored entries now exceeds
capacity, remove the least recently used entry.
get(key, now)
Returns the stored value for key if it exists and has not yet expired; otherwise returns -1.
- A successful lookup (non-expired key) promotes that entry to the most recently used position.
- If the key is found but has expired, remove it and return
-1.
Expiration boundary: an entry with deadline d is considered expired whenever now >= d. A ttl of 0 means the entry is expired immediately on any future access.
Eviction semantics: eviction is triggered only by a fresh insertion that pushes the count past capacity. At most one entry is evicted per put. The entry removed is whichever one currently occupies the least recently used position in the store — this may be an entry that has already expired but was never accessed.
Driver function
The judge calls a single function:
def ttl_lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
capacity— the maximum number of entries the cache may hold at one time.operations— a list of strings, each either"get"or"put".arguments— a list of argument lists, one per operation:- For
"get":[key, now] - For
"put":[key, value, ttl, now]
- For
- Returns a list of results, one per operation: the integer value (or
-1) for"get", andNonefor"put".
Constraints
1 <= capacity <= 10001 <= len(operations) == len(arguments) <= 10 000- Each operation is either
"get"or"put" - All keys, values,
ttl, andnowvalues are non-negative integers key,valuefit in a 32-bit signed integerttl >= 0; attlof0means the entry expires at timenow, so anygetat or after that time returns-1now >= 0; time values within a single sequence of operations are not guaranteed to be monotonically increasinggetarguments:[key, now]— exactly 2 integersputarguments:[key, value, ttl, now]— exactly 4 integers- Both
getandputmust run in O(1) average time
Examples
Example 1
Input: ttl_lru_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 10, 5, 0], [2, 20, 10, 0], [1, 1], [3, 30, 5, 1], [2, 1], [3, 1], [1, 5]])
Output: [None, None, 10, None, -1, 30, -1]
Example 2
Input: ttl_lru_cache(1, ['put', 'get', 'put', 'get', 'get'], [[7, 70, 2, 3], [7, 4], [7, 71, 5, 5], [7, 5], [7, 10]])
Output: [None, 70, None, 71, -1]
Hints
Hint 1
The two data structures you need are a hash map for O(1) key lookup and a doubly linked list to track recency order. Sentinel head and tail nodes eliminate all the edge cases around empty lists and boundary insertions.
Hint 2
You don't need a background thread or a timer to handle expiration. Check whether an entry is stale at the moment you touch it, remove it right then, and treat it as absent — this 'lazy deletion' keeps every operation O(1).
Hint 3
Eviction only needs to happen when a brand-new entry is inserted and the count exceeds capacity. Updating a live key never changes the count. The least recently used entry is always sitting just before the tail sentinel, so removing it is a constant-time pointer swap.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core data structures
Two structures work together:
- A hash map
key → nodegives O(1) access to any entry by key. - A doubly linked list ordered by recency tracks which entry is most and least recently used. Two sentinel nodes (
headandtail) sit permanently at both ends so that every real node always has valid neighbours — no boundary checks anywhere.
head.next is always the most recently used (MRU) entry; tail.prev is always the least recently used (LRU) entry.
Expiration: lazy deletion
There is no background sweep. Instead, every get and every put checks the stored deadline at the moment the key is touched. If expires_at <= now the entry is removed on the spot and treated as absent. This keeps every operation O(1) with no extra overhead.
Boundary: expired means now >= expires_at. A ttl of 0 sets expires_at = now, so the entry is immediately expired for any access at or after that timestamp.
get(key, now)
- Key absent from map → return
-1. - Key present but
expires_at <= now→ remove node, return-1. - Key present and live → move node to front (MRU), return its value.
put(key, value, ttl, now)
- Key exists and is expired → delete the stale node; treat as a missing key.
- Key exists and is live → overwrite value and deadline, move to front, return. The count is unchanged, so no eviction is needed.
- No live key → create a new node, map it, place it at the front. If
len(map) > capacity, call_unlink_and_delete(tail.prev)to evict the LRU entry.
Why this is correct
Map–list invariant: every insert adds to both map and list; every delete removes from both via the same helper. The two structures always contain identical sets of nodes.
Recency invariant: every successful access calls _move_to_front or _insert_at_front, so tail.prev is always the least recently used stored entry.
Expiration is never observable: every read path checks the deadline before returning a value or updating recency.
Eviction semantics: because expiration is lazy, a stale entry that was never accessed still occupies a slot in the map. On overflow the code simply evicts tail.prev — whatever happens to be there, live or expired. If the LRU slot is stale, evicting it is a convenient cleanup. If it is live, it is the rightful eviction candidate. This is the behaviour the test cases verify. Tracking only live entries for capacity purposes would require proactive expiry sweeps (e.g., a min-heap on expires_at) at O(log n) per operation, breaking the O(1) requirement.
Complexity
- Time: O(1) average for both
getandput. Each does a constant number of hash-map lookups/insertions and pointer updates. The driver runs in O(m) total for m operations. - Space: O(capacity) for the nodes and map. After every
putreturns, at mostcapacitynodes are stored. Sentinels add O(1).
Edge cases
geton a key that was never inserted returns-1with no side effects.expires_at == nowcounts as expired (uses<=, not<).ttl = 0: the entry is inserted (possibly evicting something), but every subsequentgetsees it as expired.puton an expired key: stale node is removed first, then a fresh node is inserted at the front, which may trigger one eviction.puton a live key: updates value and TTL, promotes to MRU, never evicts.capacity = 1: every new key evicts the previous one. The newly inserted node is at the front, sotail.previs the old node — never the one just added.
Reference solution
from typing import List, Optional
class _Node:
"""A single entry in the doubly linked list / hash map."""
__slots__ = ("key", "value", "expires_at", "prev", "next")
def __init__(self, key, value, expires_at):
self.key = key
self.value = value
self.expires_at = expires_at
self.prev = None
self.next = None
class _TTLLRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.nodes: dict = {}
# Sentinel nodes: head.next is MRU, tail.prev is LRU.
self.head = _Node(None, None, 0)
self.tail = _Node(None, None, 0)
self.head.next = self.tail
self.tail.prev = self.head
# ------------------------------------------------------------------ helpers
def _unlink_and_delete(self, node: _Node) -> None:
"""Remove node from the list and from the map."""
node.prev.next = node.next
node.next.prev = node.prev
del self.nodes[node.key]
def _insert_at_front(self, node: _Node) -> None:
"""Place node immediately after the head sentinel (MRU position)."""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _move_to_front(self, node: _Node) -> None:
"""Reorder an already-tracked node to the MRU position."""
node.prev.next = node.next
node.next.prev = node.prev
self._insert_at_front(node)
# ----------------------------------------------------------------- public
def get(self, key: int, now: int) -> int:
node = self.nodes.get(key)
if node is None:
return -1
if node.expires_at <= now: # expired: evict lazily
self._unlink_and_delete(node)
return -1
self._move_to_front(node)
return node.value
def put(self, key: int, value: int, ttl: int, now: int) -> None:
node = self.nodes.get(key)
# If stale, remove it first and fall through to the insert path.
if node is not None and node.expires_at <= now:
self._unlink_and_delete(node)
node = None
if node is not None:
# Live key: update in place, no eviction needed.
node.value = value
node.expires_at = now + ttl
self._move_to_front(node)
return
# Fresh insertion.
new_node = _Node(key, value, now + ttl)
self.nodes[key] = new_node
self._insert_at_front(new_node)
# Evict the LRU tail entry if we've gone over capacity.
if len(self.nodes) > self.capacity:
self._unlink_and_delete(self.tail.prev)
def ttl_lru_cache(
capacity: int,
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
cache = _TTLLRUCache(capacity)
results: List[Optional[int]] = []
for op, args in zip(operations, arguments):
if op == "get":
results.append(cache.get(*args))
else:
cache.put(*args)
results.append(None)
return results