Problem overview
A cache holds a limited number of entries. When it is full and a new key arrives, something has to go. An LRU (Least Recently Used) cache evicts the entry that was used longest ago, where "used" means read with get or written with put.
The class LRUCache stores int keys and int values and has three parts:
- the constructor
LRUCache(int capacity), which makes an empty cache; int get(int key), which returns the stored value, or-1for a key that is missing or was evicted. A hit makes the key the most recently used; a miss changes nothing;void put(int key, int value), which stores the value and makes the key the most recently used. Updating an existing key evicts nothing. Adding a new key to a full cache first evicts the least recently used entry.
The lesson's test code makes a cache of capacity 2, puts keys 1 and 2, reads key 1, then puts key 3. Key 2 is now the oldest, so it is the one evicted: get(2) prints -1 while get(1) and get(3) still work.
Approach: one structure for values, one for recency
A single collection can't do both jobs well in this version, so the class keeps two that always hold the same keys:
map, aMap<Integer, Integer>, answers "what is the value for this key?" and "is this key stored?";order, aList<Integer>, holds the keys sorted by use: the least recently used at index 0, the most recently used at the end.
Every use takes the key out of its current place in order and adds it at the end. Eviction is then simple: the key at index 0 is the victim. It must be removed from both structures, or the two would disagree.
Finding a key inside an ArrayList means walking the list, so get and put cost time proportional to the number of entries. That is fine for learning how the rules fit together. Faster designs replace the list with a structure that can move a key in constant time, but they follow the same rules.
Step by step
- Declare the class
LRUCacheand close its brace right away; everything else goes inside. - Add the
capacityfield as aprivate int. The constructor fills it in. - Add
mapas a privateMap<Integer, Integer>starting as a newHashMap. It stores each key's value. - Add
orderas a privateList<Integer>starting as a newArrayList. Its position in the list is the only record of how recently a key was used. - Write the constructor and, inside it, save the argument with
this.capacity = capacity. Thethis.separates the field from the parameter of the same name. - Start
getas a public method takingkeyand returning anint. - Handle a miss first: if the map doesn't contain the key, return
-1and touch nothing. - Remove the key from
orderusingInteger.valueOf(key). The wrapper matters, as the language notes below explain. - Add the key back at the end of
order: it is now the most recently used. - Return the value that the map holds for the key.
- Start
putas a publicvoidmethod takingkeyandvalue. - Handle an update: if the map already contains the key, take it out of
order, asgetdoes. There is no eviction, because the cache doesn't grow. - Handle a new key in a full cache with an
else ifwhose condition ismap.size() >= capacity. - Read the oldest key with
order.get(0)into anintnamedevict. - Remove index 0 from
orderwithorder.remove(0). - Remove
evictfrom the map. Removing it fromorderalone would leave its value behind and make the map count too high. - Store the value with
map.put(key, value), after the wholeifchain, because everyputstores, whether the key is new or not. - Add the key at the end of
order, also after the chain, so everyputmarks its key as the most recently used.
The solution in Java
class LRUCache {
private int capacity;
private Map<Integer, Integer> map = new HashMap<>();
private List<Integer> order = new ArrayList<>();
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
order.remove(Integer.valueOf(key));
order.add(key);
return map.get(key);
}
public void put(int key, int value) {
if (map.containsKey(key)) {
order.remove(Integer.valueOf(key));
} else if (map.size() >= capacity) {
int evict = order.get(0);
order.remove(0);
map.remove(evict);
}
map.put(key, value);
order.add(key);
}
}
class Solution {
public void mainFunction() {
LRUCache c = new LRUCache(2);
c.put(1, 10);
c.put(2, 20);
System.out.println("Get 1: " + c.get(1));
c.put(3, 30);
System.out.println("Get 2: " + c.get(2));
System.out.println("Get 3: " + c.get(3));
System.out.println("Miss 9: " + c.get(9));
c.put(1, 11);
System.out.println("Update 1: " + c.get(1));
c.put(4, 40);
System.out.println("Evicted 3: " + c.get(3));
System.out.println("Kept 1: " + c.get(1));
System.out.println("Kept 4: " + c.get(4));
LRUCache s = new LRUCache(1);
s.put(1, 100);
s.put(2, 200);
System.out.println("Small 1: " + s.get(1));
System.out.println("Small 2: " + s.get(2));
}
}
The Java details worth a closer look:
remove(int)againstremove(Object).Listhas tworemovemethods. Given a plainint, it removes the element at that position. Given anInteger, it removes the first element equal to it. On a list holding[5, 6, 7],remove(Integer.valueOf(7))leaves[5, 6],remove(1)leaves[5, 7], andremove(7)throws anIndexOutOfBoundsExceptionbecause there is no position 7. That is why the key is wrapped, whileorder.remove(0)deliberately uses the position version.- Autoboxing.
order.add(key)andmap.put(key, value)acceptintvalues and box them intoIntegerobjects.int evict = order.get(0)andreturn map.get(key)unbox them again. The unboxing ingetis safe because the method has already confirmed that the key is present:map.getreturnsnullfor a missing key, and unboxingnullwould throw aNullPointerException. - Private fields with initialisers. The two collections are created where they are declared, so every new
LRUCachegets its own empty ones. The constructor only has to save the capacity. - The order of the
ifchain. Theelse ifruns only for a key that isn't in the map, so the size check never triggers an eviction for an update.
Complexity
Time: O(n) per operation, where n is the number of entries (at most capacity). The map operations take constant time on average, but order.remove(Integer.valueOf(key)) scans the list to find the key, and removing from the front of an ArrayList shifts every other element left. A sequence of m operations therefore costs O(m * n) in the worst case.
Space: O(n). The map and the list each hold at most capacity keys.
Edge cases and common mistakes
- A miss must not reorder anything.
get(9)on a cache that never stored 9 returns-1and leavesorderas it was. - An update is a use. With
orderequal to[1, 3], callingput(1, 11)changes the order to[3, 1]. Key 3 is now the next victim, so the followingput(4, 40)evicts it, andget(3)afterwards gives-1. - Forgetting the map when evicting. If only
orderloses the evicted key,getwould still return its value, andmap.size()would stay at capacity forever. - Capacity 1. Each new key evicts the previous one: after
put(1, 100)andput(2, 200),get(1)is-1andget(2)is200. - Capacity 0. The lesson doesn't cover it. With this solution, the first
putfinds the map "full", callsorder.get(0)on an empty list and throws anIndexOutOfBoundsException. - Using
remove(key)withoutInteger.valueOf. It compiles, but removes by position, so the wrong key (or none, with an exception) leaves the list.
Testing
Tracing the lesson's first cache, with order and map shown after each call:
| Call | Result | order | map |
|---|---|---|---|
put(1, 10) | [1] | {1=10} | |
put(2, 20) | [1, 2] | {1=10, 2=20} | |
get(1) | 10 | [2, 1] | {1=10, 2=20} |
put(3, 30) | [1, 3] | {1=10, 3=30} | |
get(2) | -1 | [1, 3] | {1=10, 3=30} |
get(3) | 30 | [1, 3] | {1=10, 3=30} |
get(9) | -1 | [1, 3] | {1=10, 3=30} |
put(1, 11) | [3, 1] | {1=11, 3=30} | |
put(4, 40) | [1, 4] | {1=11, 4=40} |
The full output of the lesson's test code is:
Get 1: 10
Get 2: -1
Get 3: 30
Miss 9: -1
Update 1: 11
Evicted 3: -1
Kept 1: 11
Kept 4: 40
Small 1: -1
Small 2: 200
