Forward Deployed EngineeringCodingHash Maps and Linked Lists
Design and implement an LRU cache with O(1) get and put
Question 37 of 73 · Updated
On this page
- Interview-ready answer
- 1. Define the cache contract
- 2. Why combine two data structures?
- 3. Represent recency with sentinel nodes
- 4. Python implementation: hash map and doubly linked list
- How get works
- How put works
- 5. Step-by-step dry run
- 6. Correctness invariants and proof
- 7. Complexity
- 8. Python alternative: OrderedDict
- 9. Edge cases
- 10. Tested implementation verification
- 11. Concurrency and production trade-offs
- LRU versus expiration and admission
- Distributed caches
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I would combine a hash map with a doubly linked list. The hash map maps each key to its list node, providing expected O(1) lookup. The linked list maintains the order in which entries were most recently used: the least recently used entry is at the front, and the most recently used entry is at the back.
On a successful get, I locate the node through the hash map, move it to the most-recently-used end, and return its value. On a put, I either update and move an existing node or insert a new node at that end. If the cache exceeds capacity, I remove the least-recently-used node and delete its key from the map. Each operation requires a constant number of pointer changes and dictionary operations, so get and put take expected amortized O(1) time under standard hashing assumptions, with O(capacity) storage.
I would use two sentinel nodes to avoid special cases when inserting or removing the first or last real node. For application code in Python, OrderedDict is a simpler alternative. In a concurrent service, the map and recency list must be updated together under an appropriate synchronization mechanism.
1. Define the cache contract#
LRU stands for least recently used. When a cache is full and a new entry must be inserted, evict the entry that has gone the longest without a successful access or update. LRU tracks recency, not the number of times an entry has been accessed.
For this implementation, assume integer keys and values and a nonnegative integer capacity measured in entries.
| Operation | Behavior |
|---|---|
| get(key) | Return the stored value and mark the entry as most recently used; return -1 on a miss |
| put(key, value) | Insert or update the entry and mark it as most recently used |
| Eviction | On insertion beyond capacity, remove the least recently used entry |
| Capacity zero | Accept calls but store no entries |
| Negative capacity | Raise ValueError |
The conventional coding-interview problem often restricts values to nonnegative integers and requires a positive capacity. These implementations additionally handle zero capacity and negative integer values. If -1 is a valid value, a caller cannot distinguish a hit returning -1 from a miss using this API alone; use a unique miss sentinel, a found/value result or an exception in an application that needs that distinction.
A missed get does not alter the cache's recency order. Updating an existing key counts as a use but must not increase the number of stored entries. Neither operation expires entries by age; TTL is a separate feature.
2. Why combine two data structures?#
A dictionary alone answers whether a key exists and retrieves its value efficiently. But a plain lookup does not automatically record an LRU policy, and a general insertion-ordered dictionary needs deliberate reordering to represent recency.
A linked list alone can store entries in recency order and remove an endpoint efficiently. However, finding an arbitrary key requires a linear scan.
A singly linked list with a direct pointer to an arbitrary node still has difficulty removing that node without knowing its predecessor. A doubly linked list stores both neighboring pointers, so an already located node can be removed or repositioned in constant time.
| Data structure | Direct key lookup | Remove known entry | Maintain explicit recency order |
|---|---|---|---|
| Ordinary hash map | Expected O(1) | Expected O(1) | Requires additional operations or representation |
| Array or list | O(n) without an index | O(n) in the worst case for middle removal | Yes, but movement may be expensive |
| Doubly linked list | O(n) without an index | O(1) given node pointer | Yes |
| Hash map + doubly linked list | Expected O(1) | Expected O(1) overall | Yes |
An index into an ordinary array does not solve the movement problem: removing an entry in the middle can shift many elements and invalidate stored indices.
3. Represent recency with sentinel nodes#
In this lesson the head side is LRU and the tail side is MRU. The head and tail are dummy nodes; they do not represent cached keys and are never inserted into the dictionary.
The double-headed links represent the prev and next relationships between adjacent nodes. The dictionary references the same node objects as the list; it is not a second independent copy of the cache.
Initially head.next is tail and tail.prev is head. Every real entry always lies between those sentinels. To remove a real node, connect its predecessor directly to its successor in both directions. To make a node most recently used, insert it immediately before tail.
4. Python implementation: hash map and doubly linked list#
PYTHONclass Node: def __init__(self, key=None, value=None): self.key, self.value = key, value self.prev = self.next = None class LRUCache: def __init__(self, capacity): if capacity < 0: raise ValueError('negative capacity') self.capacity = capacity self.nodes = {} self.head, self.tail = Node(), Node() self.head.next = self.tail self.tail.prev = self.head def _remove(self, node): node.prev.next = node.next node.next.prev = node.prev def _append(self, node): last = self.tail.prev last.next = node node.prev, node.next = last, self.tail self.tail.prev = node def get(self, key): node = self.nodes.get(key) if node is None: return -1 self._remove(node) self._append(node) return node.value def put(self, key, value): if self.capacity == 0: return node = self.nodes.get(key) if node is not None: node.value = value self._remove(node) self._append(node) return node = Node(key, value) self.nodes[key] = node self._append(node) if len(self.nodes) > self.capacity: victim = self.head.next self._remove(victim) del self.nodes[victim.key]
The private helper _remove expects a currently linked real node. The helper _append expects an unlinked or just-detached node. They are not public methods and must not be called on sentinel nodes. All calls here are serialized. The capacity is fixed after construction.
How get works#
- Search the map for the key.
- If no node exists, return -1 without changing order.
- Otherwise detach the node from its current position and append it to the MRU end.
- Return the stored value.
Even when the node is already MRU, removing and reinserting it changes only a constant number of pointers.
How put works#
An insertion temporarily creates one extra entry before eviction, but the public operation returns with the capacity invariant restored. If the key already exists, no eviction is required because the number of entries is unchanged.
5. Step-by-step dry run#
Suppose the capacity is two. List order below is LRU to MRU.
| Operation | Returned value | Order after operation | Explanation |
|---|---|---|---|
| put(1, 10) | — | 1:10 | First entry |
| put(2, 20) | — | 1:10, 2:20 | Key 2 is MRU |
| get(1) | 10 | 2:20, 1:10 | Key 1 is refreshed |
| put(3, 30) | — | 1:10, 3:30 | Evict key 2 |
| get(2) | -1 | 1:10, 3:30 | Miss; no change |
| put(1, 15) | — | 3:30, 1:15 | Update and refresh key 1 |
| put(4, 40) | — | 1:15, 4:40 | Evict key 3 |
| get(3) | -1 | 1:15, 4:40 | Miss |
The distinction between FIFO and LRU is visible after get(1). FIFO would still consider key 1 the oldest insertion and might evict it. LRU records the access, so key 2 becomes the eviction candidate.
6. Correctness invariants and proof#
At the end of each public operation:
- Map-list bijection: Each map key refers to exactly one real list node with the same key, and every real list node is represented by exactly one map entry.
- Link integrity: Every adjacent pair of nodes agrees on its next and prev pointers. Traversing from head reaches tail without a cycle or an omitted real node.
- Recency order: Real nodes are arranged from least recently used to most recently used according to successful gets and puts.
- Capacity: The number of map entries and real nodes is at most capacity.
Initially the map is empty and the sentinels are linked directly. All four invariants hold.
On a get miss, no mutation occurs. On a hit, the node already exists in the map and list. Detaching it and appending it leaves membership unchanged, restores its links, and makes it the most recently used entry. Other entries retain their relative order.
On an update, the same reasoning applies while the value is changed. On a new insertion, one node is added to both structures and becomes MRU. If the previous cache was full, exactly one excess entry exists. By the recency invariant, head.next is the least recently used real node. Removing that node and deleting its map entry restores the capacity and bijection invariants. The remaining nodes preserve their order.
By induction, every completed operation maintains these invariants, returns the required value, and selects the correct eviction candidate. This reasoning assumes serialized calls and the stated integer-key contract, with no unhandled exceptional interruption during the internal mutations.
7. Complexity#
Let C be the fixed capacity.
- get: one expected constant-time dictionary lookup and a constant number of pointer assignments. Expected amortized O(1).
- put: a constant number of dictionary operations, pointer assignments and at most one eviction. Expected amortized O(1).
- Storage: at most C key-to-node mappings and C real nodes plus two sentinels. O(C + 1), usually expressed as O(C).
- Temporary storage per operation: O(1), excluding occasional dictionary resizing or allocation behavior.
A hash map's expected amortized time is not an unconditional worst-case guarantee. Collisions, resizing and the cost of hashing unusual or large keys affect actual performance. The usual interview model treats keys and values as fixed-size items and hashing as expected constant-time. A single dictionary resize may take more than constant time, but its cost is amortized over operations.
The cache's entry bound is not a byte bound. If entries hold large strings, arrays or references to other objects, the actual retained memory depends on those objects.
8. Python alternative: OrderedDict#
Python's collections.OrderedDict provides explicit reordering and endpoint removal. It is a good concise implementation when using standard-library data structures is allowed.
PYTHONfrom collections import OrderedDict class OrderedLRU: def __init__(self, capacity): if capacity < 0: raise ValueError('negative capacity') self.capacity = capacity self.data = OrderedDict() def get(self, key): if key not in self.data: return -1 self.data.move_to_end(key) return self.data[key] def put(self, key, value): if self.capacity == 0: return self.data[key] = value self.data.move_to_end(key) if len(self.data) > self.capacity: self.data.popitem(last=False)
move_to_end marks an existing entry as most recently used. popitem(last=False) removes the first, least recently used entry. Explicit movement is necessary because updating the value associated with an existing key does not by itself implement the required access-order policy.
Under ordinary hash-table assumptions, these operations have the expected amortized constant-time behavior required for the interview in the conventional Python implementation. An ordinary insertion-ordered dict also supports some LRU-style idioms, but OrderedDict expresses the reordering intent more clearly. Do not confuse preservation of insertion order with automatic access ordering.
For memoizing a pure function, functools.lru_cache is another built-in option. It provides a bounded function-result cache rather than the arbitrary key/value get-and-put interface in this problem. It may evaluate the wrapped function more than once during concurrent cache misses even when its internal cache data structure remains coherent; a single-flight guarantee is a different feature.
9. Edge cases#
| Scenario | Required behavior |
|---|---|
| Capacity 0 | put does nothing; get always misses |
| Capacity 1 | Adding a different key evicts the previous key |
| Existing key updated at full capacity | No extra eviction; updated node becomes MRU |
| Repeated get on the MRU node | Value and order remain correct |
| Get on a missing key | No insertion or recency change |
| Key 0 or value 0 | Valid stored entry; do not test value truthiness |
| Stored -1 | Hit still refreshes recency; result is ambiguous with miss under this interface |
The sentinel nodes eliminate most empty-list and single-node pointer cases. The zero-capacity guard prevents trying to retain any new entry. Deletion from both the map and list is essential: forgetting either side produces ghost entries, incorrect capacity accounting or a stale lookup.
10. Tested implementation verification#
Both exact classes above were executed locally using Python 3.13.5. The independent reference model used a linear list of key/value pairs from LRU to MRU. It searched the list directly, removed and reinserted matching entries, and evicted from the front.
The tests covered:
- Every operation sequence of length zero through four over nine operations: get on three keys, and put on those three keys with either of two values.
- Every capacity from zero through three for each exhaustive sequence: 29,524 sequences per implementation.
- 200 seeded randomized sequences of 100 operations each per implementation, with capacities from zero through eight, negative and positive keys, and values including -1 and an integer of magnitude 10^100.
- Two negative-capacity rejection checks, one per implementation.
After each operation, the harness verified the returned result, complete cache state, exact recency order and capacity. For the custom linked list it additionally checked forward and backward adjacency, absence of repeated node identities, sentinel integrity and exact map-to-node correspondence.
All 59,450 combined sequence and invalid-capacity checks passed (29,724 sequences per implementation, plus two invalid-capacity checks). These are sequential local correctness tests, not performance benchmarks or multithreaded stress tests.
11. Concurrency and production trade-offs#
The custom and OrderedDict implementations are intentionally single-threaded. A successful get changes the list, so it is a write to cache metadata even though the external API appears read-only. Two concurrent accesses could interleave map and list mutations and break invariants, or produce an eviction inconsistent with a serialized LRU order.
For a shared in-process cache, protect each complete get and put with the same lock or an equivalent synchronization design. Protecting only dictionary access is insufficient. A read/write lock does not permit ordinary concurrent get hits unless recency updates are separately synchronized under an explicitly defined policy. The Python GIL is not a transaction across several operations.
Do not hold a global cache lock across slow network or database loads. A cache-aside application can release the lock, fetch data and recheck before publishing the result, but must address races with invalidation and concurrent writes. Request coalescing or a per-key single-flight mechanism can reduce duplicate work on misses. Use timeouts and cleanup so a failed loader does not leave callers blocked indefinitely.
For high-throughput caches, strict global LRU can create metadata contention. Sharding by key, segmented LRU and approximate eviction can improve throughput at the cost of exact global ordering or hit-rate differences. Measure cache effectiveness and synchronization overhead rather than assuming one eviction algorithm is universally optimal.
LRU versus expiration and admission#
LRU decides which entry to evict when capacity is constrained. TTL determines when an entry expires, irrespective of access frequency. Invalidation determines when an underlying source or policy change makes a cached value unusable.
A production cache may need all three. Efficient arbitrary TTL expiration may require an additional scheduling or expiry structure; the simple two-structure implementation does not provide that behavior. An entry that is frequently accessed can still be stale. Admission controls can prevent one-time scans of many unique entries from evicting a useful working set.
Distributed caches#
An in-process cache exists separately in each application replica. Different replicas may retain different values and recency orders. A shared cache service can offer a common lookup path, but introduces network latency, availability, consistency and operational considerations. A distributed cache may implement approximate or sampled LRU rather than an exact global ordering. Verify the chosen system's actual eviction and expiration behavior.
For a customer-facing FDE integration, treat cache keys as part of the data and authorization contract. Scope them by tenant, relevant user permissions, model or configuration, and source version when needed. Do not assume a cache hit bypasses current authorization checks. Define invalidation, stale-data behavior, retention and safe fallback if the cache fails.
Monitor hit and miss rates, evictions, retained bytes, load latency, concurrent misses, lock wait, and end-to-end customer success and latency. A higher hit rate is not useful if the cache returns stale, unauthorized or otherwise incorrect results.
Likely interviewer follow-ups#
Why can't I use only a hash map? Lookup is efficient, but a plain get does not maintain explicit recency. You need a mechanism to move touched entries and remove the least recent one efficiently.
Why a doubly linked list rather than a singly linked list? Given a node pointer, the doubly linked list also provides its predecessor. This makes arbitrary detachment and reinsertion constant-time without searching.
What if a put overwrites an existing key? Update the value and move that same node to MRU. It does not create an additional entry.
What if get misses? Return the defined miss result and preserve the existing recency order.
Is O(1) worst-case guaranteed? No. The list mutations take constant time given a node, but dictionary operations are typically analyzed as expected amortized constant time.
What is the difference between LRU and LFU? LRU ranks by most recent use; LFU ranks by access frequency, with a separate tie policy. They require different bookkeeping and can perform differently under changing access patterns.
Is the implementation thread-safe? No. Synchronize the complete operation, including recency and map changes, or choose an appropriate tested concurrent cache.
How would I add a TTL or variable-sized entries? First define expiry, refresh and capacity semantics. Byte-based eviction can require removing several entries for one insertion, changing the per-operation time bound; expiry also requires deliberate cleanup and scheduling.
Interview takeaway#
Use a hash map for direct access and a doubly linked list for recency. Keep the map and list consistent, refresh an entry on successful get or put, and evict the LRU node when a new insertion exceeds capacity. Prove the invariants, test boundary cases and qualify the O(1) claim as expected amortized under normal hashing assumptions.
References
- 1.
- 2.
- 3.
- 4.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models