Quick revision
The short answer
We combine a HashMap from key to node with our own doubly linked list of nodes ordered by recency: the most recent node sits just after a sentinel head, the least recent just before a sentinel tail. get() finds the node in the map, unlinks it and reinserts it after head; put() does the same or creates a node, and evicts tail.prev when the size exceeds the capacity. Both are O(1). For concurrency, one lock around both methods is correct but serializes reads, which is why production caches such as Caffeine buffer access events instead.
What to remember
In this answer, we saw that an O(1) LRU cache needs a HashMap for lookup and a doubly linked list for recency, with the map pointing at the nodes. Sentinel head and tail nodes remove every null check, so insertion is always after head and eviction always takes tail.prev. get() and put() are a lookup plus a few pointer moves. A single lock makes the cache correct but serializes reads, and production caches avoid that by buffering access events and applying them in batches.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We combine a HashMap from key to node with our own doubly linked list of nodes ordered by recency: the most recent node sits just after a sentinel head, the least recent just before a sentinel tail. get() finds the node in the map, unlinks it and reinserts it after head; put() does the same or creates a node, and evicts tail.prev when the size exceeds the capacity. Both are O(1). For concurrency, one lock around both methods is correct but serializes reads, which is why production caches such as Caffeine buffer access events instead.
Why this question is asked
Writing an LRU cache from scratch is a classic coding exercise because it needs two data structures working together, careful pointer handling, and a clear explanation of why each operation is constant time. In real work the same pattern appears in connection pools, page caches and rate limiters, so understanding it pays off beyond the interview. In this answer, we will see why one structure is not enough, build the node list with sentinels, write get() and put(), trace a short run, and then discuss making it safe for many threads and adding a time-to-live.
1Why We Need Two Structures
An LRU cache, least recently used, must do two things fast. It must find the value for a key, and it must know which entry was used least recently so it can evict that entry when the cache is full.
A HashMap gives us the first in O(1), meaning the cost does not grow with the number of entries, but it has no idea of order. A linked list ordered by recency gives us the second: the least recent entry is always at one end. But finding a key in a list means walking it, which is O(n). Moving an entry to the front is also only cheap if we already hold a reference to its node and can unlink it without searching.
So we use both. The HashMap maps each key to its node in the list, and the list keeps the nodes in recency order. The list must be doubly linked, each node pointing to the previous and the next node, because unlinking a node in O(1) needs access to its predecessor.
| Structure | Holds | Gives us in O(1) |
|---|---|---|
HashMap<K, Node> | key -> node in the list | find the node for a key |
| Doubly linked list | nodes from most to least recent | unlink a node, insert at the front |
| Sentinel head | a dummy node before the most recent | insert without null checks |
| Sentinel tail | a dummy node after the least recent | find the eviction victim: tail.prev |
2How Sentinel Nodes Simplify the Code
A sentinel is a dummy node that holds no key or value and is never removed. We create two of them, head and tail, and link them to each other when the cache is empty. Every real node then lives between them.
The reason is that without sentinels, every insertion and removal has special cases: inserting into an empty list, removing the only node, removing the first or the last node, each needing checks for null and updates to separate first and last fields. With sentinels, every real node always has a real prev and a real next, so the same four pointer assignments work in every case. Insertion is always between head and head.next. Removal is always node.prev.next = node.next and node.next.prev = node.prev. The least recently used node is always tail.prev, and the cache is empty exactly when head.next == tail.
3Writing get() and put()
Here is the full cache. The two private helpers do all the pointer work, and the public methods only combine them.
Notice that each node stores its own key. When we evict tail.prev, we only have the node, and we need its key to remove the map entry as well. Forgetting this is the most common bug in this exercise: the list shrinks but the map keeps growing.
Every step is O(1): one HashMap lookup, a fixed number of pointer assignments, and at most one HashMap removal. Nothing depends on how many entries the cache holds.
4Tracing a Short Run
With capacity 2, we can follow the list between the sentinels after each call.
- Look up the key in the map
- Node found?Yesupdate the value, unlink it, insert after head, doneNocreate a node, add it to the map, insert after head
- map.size() > capacity?Yesunlink tail.prev and remove its key from the mapNodone
3 steps in order. Play them, or step through them one at a time.
get() is the first branch without the value update.
The get("a") call moved a to the front, so b became the least recent entry and was the one evicted when c arrived. That is the whole LRU behaviour in four lines.
5Making It Safe for Concurrent Use
This class is not thread-safe. Both get() and put() change the list, so two threads running at once can interleave their pointer assignments and leave nodes unreachable or linked in a loop.
The simplest correct fix is one lock around both methods: mark them synchronized, or use a ReentrantLock. That is correct, and for a cache used by a few threads it is enough. But there is a catch: every get() is a write, because it moves a node, so a read-write lock cannot help, and all readers line up behind one lock. Under high load, threads spend more time waiting for the lock than doing the work.
Production caches solve this differently. Caffeine, for example, stores entries in a ConcurrentHashMap so lookups need no global lock, and records each access in a small buffer instead of reordering the list immediately. A single thread later drains the buffers and applies the reordering in a batch, under a lock that readers rarely wait for. If a buffer is full, some access events are simply dropped, which slightly blurs the recency order but keeps reads fast. That trade, approximate order for near-lock-free reads, is what makes such caches scale. In an interview, I would write the synchronized version and then explain this design rather than try to build it on a whiteboard.
6Follow-up questions
How would you add a time-to-live per entry?
Each node gets an expiresAt field, set from a Clock when the value is put, so tests can control time. get() checks it: if the node has expired, we unlink it, remove it from the map and return null, which is lazy expiry. Lazy expiry alone lets dead entries take space, so we also add cleanup: either a periodic sweep from the tail, or a priority queue or timer wheel ordered by expiry time that we drain on each put. Caffeine supports this directly with expireAfterWrite for a fixed time-to-live and expireAfter with an Expiry for a time per entry.
Why must the list be doubly linked?
To unlink a node in O(1) we must change its predecessor's next pointer. In a singly linked list we would have to walk from the start to find the predecessor, which is O(n). The prev pointer gives it to us directly.
Could we use a ConcurrentHashMap and keep the rest unchanged?
No. The map would be safe, but the linked list would still be changed by several threads at once. The map and the list must change together as one step, so they need a common lock, or a design like Caffeine's where only one thread ever changes the order.
7Conclusion
In this answer, we saw that an O(1) LRU cache needs a HashMap for lookup and a doubly linked list for recency, with the map pointing at the nodes. Sentinel head and tail nodes remove every null check, so insertion is always after head and eviction always takes tail.prev. get() and put() are a lookup plus a few pointer moves. A single lock makes the cache correct but serializes reads, and production caches avoid that by buffering access events and applying them in batches.
Open with
I would use two structures together. A HashMap from key to node gives me O(1) lookup, and a doubly linked list of those nodes keeps them in recency order, most recent next to the head, least recent next to the tail.
Then, if they want more
I add two sentinel nodes, head and tail, which hold no data and are never removed.
They remove all the null checks: inserting is always between head and head.next, unlinking is always node.prev.next equals node.next and the reverse, and the eviction victim is always tail.prev. get looks up the node, unlinks it, inserts it after head and returns the value. put either updates an existing node and moves it to the front, or creates a node, adds it to the map and the list, and if the size is over capacity, unlinks tail.prev and removes its key from the map, which is why each node stores its key.
Everything is a constant number of operations. For concurrency, I would start with one lock around get and put. It is correct, but because every get reorders the list, all reads serialize, and a read-write lock does not help.
Caffeine avoids this by using a concurrent map and recording accesses in buffers that one thread applies later, so I would use Caffeine in production.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement an LRU cache in Java without LinkedHashMap, with O(1) get and put. Explain...": https://scrivio-interview-library.netlify.app/java/coding-problems/3f04778704/