Quick revision
The short answer
An LRU cache with O(1) get and put is a design problem solved by combining two structures. A HashMap from key to node finds any entry in O(1), and a doubly linked list keeps the entries in order of use, most recent at the front, so moving an entry to the front and evicting the last one are a few pointer changes. Both get and put run in O(1) time with O(capacity) space.
The solution
What it costs
| Approach | get | put | What keeps the order |
|---|---|---|---|
| Map with time stamps, scan to evict | O(1) | O(n) | stamps, never sorted |
| Map plus a list of keys in use order | O(n) | O(n) | list, found by searching |
| Map into a doubly linked list | O(1) | O(1) | list, reached through the map |
What to remember
We designed an LRU cache with O(1) get and put. The time stamp brute force gets in O(1) but scans every entry to evict, because it records the order of use without keeping it. A doubly linked list keeps that order with O(1) moves and removals, a HashMap from key to node reaches any entry in O(1), nodes store their keys so eviction can clean the map, and sentinels remove every null check. The clue to remember is a list of operations that must all be O(1) where no single structure does every job: write the jobs down, give each one to a structure, and let the structures point at the same nodes.
1What the cache must do, starting from a small desk
Imagine studying at a small desk that has room for only two books, with a big shelf of books across the room. When you need a book, you first look on the desk, because that is quick. Every time you use a book, you put it on top of the pile on your desk. When the desk is full and you need a book that is not there, one book must go back to the shelf, and the sensible choice is the one at the bottom of the pile, the book you have gone longest without touching.
That desk is a cache. A cache is a small, fast store that keeps a few items so we do not have to fetch them from somewhere slow. Its capacity is how many items it can hold, two in our example. When it is full and a new item must come in, it evicts one, meaning it throws it out. An LRU cache, short for least recently used, always evicts the item that has gone longest without being used.
Our cache has two operations. get(key) returns the value stored for the key, or -1 if the key is not there, and it counts as a use of that key. put(key, value) stores the value; if the key is already there it updates it, and either way that counts as a use. If the key is new and the cache is full, put first evicts the least recently used key. Both operations must run in O(1) time, meaning their cost must not grow with the number of entries.
Let us do the example by hand with capacity 2. put(1, 10) and put(2, 20) fill the desk; key 2, used last, is on top. get(1) returns 10 and puts key 1 on top, so key 2 is now at the bottom. Then put(3, 30) brings a new key into a full cache, so key 2 goes back to the shelf, and get(2) returns -1. The picture shows the desk just before that eviction.
Each cell is key:value. The entries are drawn in order of use, the most recently used on the left.
- capacity
- 2
- next call
- put(3, 30)
- will evict
- key 2
1Key 1 was just read by
get(1), so it is the most recently used. Key 2 has gone longest without use, soput(3, 30)must evict it.
What to assume
- Is the capacity at least 1?
- We assume so and reject anything smaller.
- Does updating an existing key count as a use?
- Yes.
- Does a get that misses change anything?
- No.
- Are keys and values ints, and is -1 safe as the answer for a miss?
- We assume both.
- Will several threads use the cache at once?
- We assume one thread.
A careful candidate settles a few things before coding. Is the capacity at least 1? We assume so and reject anything smaller. Does updating an existing key count as a use? Yes. Does a get that misses change anything? No. Are keys and values ints, and is -1 safe as the answer for a miss? We assume both. Will several threads use the cache at once? We assume one thread and discuss locking at the end.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a pattern of combining two structures
A beginner's first thought is a HashMap, and it is a good thought. A HashMap is like the index at the back of a book: given a key, it tells us at once where the value is. So get is easy. But when the cache is full, which key do we throw out? A HashMap has no idea which key was used longest ago; it does not keep any order at all.
So let us read the question slowly and take its clues one at a time. The first clue is get and put both in O(1). It tells us that every job these operations need must be done in constant time. A good habit in design questions is to write those jobs down before choosing anything.
The second clue is least recently used. It tells us the cache needs an order, the order of use, and that this order changes on every get and every put, because each use moves a key to the most recent position. So one job is moving any entry, wherever it is, to the front of an order.
The third clue is capacity, with eviction. When full, we must find and remove the entry at the other end of that order, the least recently used one. Written out, the jobs are: find an entry by key, move an entry to the front, and remove the entry at the back, all in O(1).
These clues point to the designing data structures pattern. Its method is to list every job, find a structure that does each job in the required time, and, when no single structure does them all, combine two so that they point at the same objects. Here a hash map finds entries by key, and a doubly linked list, a chain of nodes where each node knows both its neighbours, moves and removes nodes in O(1). The rule to carry to new problems is to list the jobs first and choose the structures second; the same rule builds a min stack, an LFU cache and a set with O(1) random removal.
Some tools look tempting but miss the target. A priority queue or a TreeMap ordered by time of last use finds the oldest entry, but changing an entry's position costs O(log n). An ArrayList keeps an order, but moving an element to the front shifts everything else, O(n).
3The honest first attempt, a time stamp on every entry
The brute force, the first version that works, keeps a HashMap from each key to an entry holding its value and a time stamp. The stamp comes from a counter, clock, that goes up by one on every use, so a bigger stamp means more recently used. get refreshes the stamp. put, when the cache is full and the key is new, looks at every entry, finds the one with the smallest stamp, and removes it.
Let us do it by hand. put(1, 10) stamps key 1 with 1, and put(2, 20) stamps key 2 with 2. get(1) returns 10 and restamps key 1 with 3. put(3, 30) finds the cache full, scans the stamps, 3 for key 1 and 2 for key 2, and removes key 2, the smallest. That is the right answer.
Now let us count. get does one map lookup and one map write, so it is O(1) on average. But each put on a full cache reads every stamp to find the oldest, so put is O(n) for a cache of n entries. A cache of a million entries would read a million stamps on every miss, which is exactly the moment we are already paying for a slow fetch.
Where does the waste come from? The stamps record the order of use, but they do not keep the entries sorted by it, so every eviction rediscovers the oldest entry from scratch. We might try keeping a list of keys in use order instead. Then eviction is easy, since the oldest key is at the end, but each get must find its key in the list to move it, and that search is O(n) again. The order must be kept, not recomputed, and we must also be able to reach any entry's place in the order without searching.
4Getting to a hash map that points into a doubly linked list
Let us take the two problems one at a time. First, we need an order where removing an entry from the middle, adding one at the front, and removing the one at the back are all O(1). A linked list can do this, as long as we are already holding the node, because unlinking a node only means joining its two neighbours, and adding one only means changing the links around the front.
Now the question every beginner asks. Why must the list be doubly linked, with prev as well as next? Let us try a singly linked list and see what goes wrong. To unlink key 1 we must change the next of the node before it. In a singly linked list a node does not know which node comes before it, so we would have to walk from the head to find it, and that walk is O(n). With prev, the node tells us its neighbour directly.
Second, we need to reach the node for a key without searching the list. That is the hash map's job, with one change from the brute force: instead of storing values, the map stores references to the list nodes. So get(key) asks the map for the node in O(1), unlinks it, adds it at the front, and returns its value. The picture shows those link changes for get(1) on our example, with the list before the call running head -> 2:20 -> 1:10 -> tail.
The four boxes are the two sentinels and the two entries. Only the next arrows are drawn; the prev references are listed on the right.
- 1.prev
- 2:20
- tail.prev
- 1:10
1Before
get(1), the list runs head -> 2:20 -> 1:10 -> tail, so key 2 is the most recent and key 1 the least recent.- 2.next
- tail
- tail.prev
- 2:20
2
unlink(node)joins the two neighbours of key 1: 2:20 now points to tail, andtail.previs 2:20. Key 1 is out of the chain, though its own arrow still points at tail.- 1.next
- 2:20
- 1.prev
- head
3
addFrontstarts with n.next =head.nextand n.prev = head, so key 1 points at 2:20 and back at head. The chain from head has not changed yet.- head.next
- 1:10
- 2.prev
- 1:10
- lru
- tail.prev = 2:20
4Then
head.next.prev= n andhead.next= n hook key 1 in. Following the arrows from head now gives 1:10 -> 2:20 -> tail.
You may have noticed two boxes called head and tail that hold no data. They are sentinels, dummy nodes that are always there. Because of them every real node always has a node before it and a node after it, so unlink and addFront never need to check for null, and the least recently used entry is always simply tail.prev.
There is one more beginner trap, and it is the classic bug in this problem. When put evicts tail.prev, it must also remove that key from the map. But the map is keyed by key, and the node is all we have, so the node must store its own key as well as its value. Forget to remove it, and the map keeps growing and later hands back a node that is no longer in the list.
Why is the whole design correct? We keep one promise: the map and the list hold exactly the same entries, and the list runs from most recently used after head to least recently used before tail. get and an update keep it by moving the touched node to the front; a new key on a full cache removes tail.prev from both structures before adding the new node to both. Every step is a fixed number of link changes and map operations, so get and put are O(1).
5Following the cache through ten calls
The picture follows a cache of capacity 2 through ten calls, the example from the first section and a few more. Each frame shows the list after one call, from head to tail, with mru on the most recently used entry and lru on the least, and the panel shows what the call returned and which keys the map holds. A miss leaves the entries greyed out, because nothing changes.
Each frame shows the list after one call, from the sentinel head to the sentinel tail. mru marks the most recently used entry and lru the least.
- call
- put(1, 10)
- returns
- nothing
- map keys
- 1
1
put(1, 10)finds no key 1 and the cache is not full, so it makes a node and adds it just after head. The map now holds key 1.- call
- put(2, 20)
- returns
- nothing
- map keys
- 1, 2
2
put(2, 20)adds key 2 at the front. The list runs 2 then 1, so key 1, just before tail, is the least recently used.- call
- get(1)
- returns
- 10
- map keys
- 1, 2
3
get(1)finds key 1 in the map, unlinks its node and adds it at the front, then returns 10. Now key 2 is next to go.- call
- put(3, 30)
- returns
- nothing
- map keys
- 1, 3
- evicted
- key 2
4
put(3, 30)is a new key and the cache is full, so it evictstail.prev, key 2, from the list and from the map, then adds key 3 at the front.- call
- get(2)
- returns
- -1
- map keys
- 1, 3
5
get(2)finds no key 2 in the map, so it returns -1 and changes nothing. Key 2 really did leave both structures.- call
- put(1, 15)
- returns
- nothing
- map keys
- 1, 3
6
put(1, 15)finds key 1, so it updates the value to 15 and moves the node to the front. Updating counts as a use, and nothing is evicted.- call
- put(4, 40)
- returns
- nothing
- map keys
- 1, 4
- evicted
- key 3
7
put(4, 40)is a new key and the cache is full, so it evictstail.prev, which is now key 3, and adds key 4 at the front.- call
- get(3)
- returns
- -1
- map keys
- 1, 4
8
get(3)misses and returns -1, because key 3 was evicted a moment ago.- call
- get(1)
- returns
- 15
- map keys
- 1, 4
9
get(1)hits, moves key 1 to the front and returns 15, the updated value.- call
- get(4)
- returns
- 40
- map keys
- 1, 4
10
get(4)hits, moves key 4 to the front and returns 40. Every call touched only a few links, never the whole cache.
Let us read the important frames back. The third frame, get(1), is the one that decides the first eviction: it moves key 1 to the front, so in the fourth frame put(3, 30) finds key 2 sitting on tail.prev, and key 2 leaves both the list and the map. The fifth frame proves it, since get(2) returns -1.
The sixth frame shows that an update is a use. put(1, 15) changes the value and moves key 1 to the front, so when put(4, 40) needs room, the entry on tail.prev is key 3, not key 1. If you trace a cache by hand in an interview, these two moments are the ones to say aloud.
6The complete Java program
Here is the full class. It has a private Node with key, value, prev and next, a HashMap from key to node, the two sentinels, the two operations, and two small helpers, unlink and addFront, which hold all the pointer work. The main method runs the ten calls from the picture, and the comment on each printing line shows what it prints.
Let us read it in the order it runs. The constructor rejects a capacity below 1 and then links head and tail to each other, so the list starts empty but already has its two sentinels. From now on every real node will sit between them.
get asks the map for the node. If there is none, it returns -1 and touches nothing. Otherwise it calls unlink, which joins the node's two neighbours with n.prev.next = n.next and n.next.prev = n.prev, then addFront, which puts the node just after head, and finally returns the value.
addFront is the one place where the order of lines matters. It first sets the new node's own links, n.next = head.next and n.prev = head, while head.next still refers to the old front. Only then does it change the neighbours, head.next.prev = n and head.next = n. If we swapped those last two lines, head.next would already be n when we set head.next.prev, so the new node's prev would point to itself and the old front node would keep a stale prev.
put first asks the map whether the key exists. If it does, it updates the value, moves the node to the front, and returns, so an update never evicts. If the key is new and the map is full, it takes tail.prev, unlinks it, and removes lru.key from the map, which is why each node carries its key. Then it makes the new node, puts it in the map, and adds it at the front. So main prints 10, -1, -1, 15 and 40.
7How much it costs, and the cases at the edges
Let us count on the example first. Each of the ten calls did at most one map lookup, one map insert or remove, and two small helpers of two and four link changes, whether the cache held one entry or two. That does not change with a bigger cache, so get and put are O(1), with the usual note that a hash map lookup is O(1) on average. The map and the list each hold at most capacity entries, so the space is O(capacity).
| Approach | get | put | What keeps the order |
|---|---|---|---|
| Map with time stamps, scan to evict | O(1) | O(n) | stamps, never sorted |
| Map plus a list of keys in use order | O(n) | O(n) | list, found by searching |
| Map into a doubly linked list | O(1) | O(1) | list, reached through the map |
A capacity below 1 is rejected in the constructor with IllegalArgumentException. With capacity 1, every new key evicts the one before it, and thanks to the sentinels that path is the same code as any other: tail.prev is the only real node.
Updating an existing key never evicts, because the number of entries does not change, which is why put returns early in that branch. A get that misses returns -1 and leaves the order alone.
8Follow-up questions
Can Java's LinkedHashMap do this for us?
Yes. A LinkedHashMap created with new LinkedHashMap<>(capacity, 0.75f, true) keeps its entries in access order instead of insertion order, and if we override removeEldestEntry to return size() > capacity, it evicts the least recently used entry after each put. Inside it is the same design we built, a hash table whose entries are also linked in a doubly linked list. It is worth mentioning in an interview, but the interviewer usually wants the hand-built version to see the pointer work.
How would you make the cache safe for several threads?
The simplest correct answer is one lock around get and put, for example by making both methods synchronized, because even get changes the list, so two threads could tangle the links. That makes every call wait its turn, so under heavy load we can split the cache into several segments chosen by the key's hash, each with its own lock and its own list. That trades a strict global order for speed. Libraries such as Caffeine go further and record uses in buffers so that reads rarely wait for a lock.
What changes for an LFU cache, which evicts the least frequently used key?
The jobs change, so the structures change. We still map key to node, but we also count uses per key and must find the smallest count in O(1). The usual design keeps one doubly linked list per count, a map from count to list, and the smallest count in a variable. A use moves a node from the list for count c to the list for c + 1, and eviction takes the least recent node from the list for the smallest count. The method is the same: list the jobs, then pick a structure for each.
9Conclusion
We designed an LRU cache with O(1) get and put. The time stamp brute force gets in O(1) but scans every entry to evict, because it records the order of use without keeping it. A doubly linked list keeps that order with O(1) moves and removals, a HashMap from key to node reaches any entry in O(1), nodes store their keys so eviction can clean the map, and sentinels remove every null check. The clue to remember is a list of operations that must all be O(1) where no single structure does every job: write the jobs down, give each one to a structure, and let the structures point at the same nodes.
Open with
Let me confirm the behaviour: a fixed capacity, get returns the value or minus one, put inserts or updates, both count as a use, and a new key on a full cache evicts the least recently used one, all in O(1).
Then, if they want more
A first version keeps a hash map from key to value plus a last-used time stamp; get is O(1), but eviction scans every entry for the oldest stamp, so put is O(n). I need three jobs in constant time: find an entry by key, move an entry to the most recent position, and remove the least recent one.
A hash map does the first, and a doubly linked list does the other two when I already hold the node. So the map stores key to node, and the list runs from most to least recent between a dummy head and a dummy tail. On get, I find the node, unlink it and add it after head.
On put for an existing key, I update the value and move it. For a new key when full, I remove tail.prev from the list and its key from the map, which is why nodes keep their keys, then add the new node to both.
It must be doubly linked so I can unlink without searching for the previous node, and the sentinels remove null checks. Both operations are O(1), and space is O(capacity). LinkedHashMap with access order gives the same design.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 69 times in that collection. How it is counted
- Official documentation
- HashMap (Java 21), java.util, package documentation
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 "Design and implement an LRU cache whose get and put both run in O(1) time.": https://scrivio-interview-library.netlify.app/data-structures/solutions/design-and-implement-an-lru-cache-whose-get-and-put-both-run-in-1420a6/
Coding patterns, question 15 of 15 Back to the path
More designing data structures questions