Problem overview
A cache keeps a few recent results close at hand, and it can only hold a limited number of entries. An LRU (Least Recently Used) cache handles a full cache by throwing away the entry that was used longest ago. The lesson asks for a class LRUCache that stores integer keys with integer values.
new LRUCache(capacity) makes an empty cache. get(key) returns the stored value, or -1 when the key is missing, and a hit counts as a use. put(key, value) stores a value, and the key becomes the most recently used. Putting an existing key only replaces its value. Putting a new key into a full cache first evicts the least recently used entry.
The example uses a cache of capacity 2. After put(1, 10) and put(2, 20), reading key 1 makes key 2 the oldest. Then put(3, 30) evicts key 2, so get(2) returns -1 while keys 1 and 3 are still there.
Approach: two structures that always hold the same keys
The class keeps two fields. A Map called map answers "is this key stored, and what is its value?" quickly. An array called order remembers when each key was used: the least recently used key sits at the front and the most recently used at the end. Every use moves a key to the end, so the front is always the next one to evict.
The two fields must describe the same set of keys. Every change to one needs a matching change to the other: removing a key from order without deleting it from the map leaves a value that can never be evicted, and the other way round leaves a key that order doesn't know about.
This version scans order on every operation, so each get and put costs time proportional to the number of stored keys. That is fine for learning the rules. Solutions that need constant time per operation combine a hash map with a doubly linked list instead.
Step by step
- Declare the class and close its brace at once, so every later step has a place to go.
- Add the
capacityfield. A class field declared in the body, with no value yet. The constructor fills it in. - Add
map, a field that starts as an emptyMap. - Add
order, a field that starts as an empty array. - Write the constructor with one parameter and save it in
this.capacity. - Start
get(key). On a miss,return -1immediately, with no change toorder, since a miss is not a use. - On a hit, move the key to the end. First rebuild
this.orderwithfilter, keeping every key that is not this one. Thenpushthe key back on the end. - Return the stored value with
this.map.get(key). - Start
put(key, value)with the update case. If the map already has the key, take the key out oforderwith the samefilter. Nothing is evicted, because an update takes no new room. - Add the eviction case as an
else if: the key is new andthis.map.sizeis at leastthis.capacity. Useshift()to remove the front key oforder, and delete that key from the map too. - Store the value after the whole
ifchain, because both new keys and updates need it. - Push the key onto the end of
order, again for both cases.
The solution in JavaScript
class LRUCache {
capacity;
map = new Map();
order = [];
constructor(capacity) {
this.capacity = capacity;
}
get(key) {
if (!this.map.has(key)) return -1;
this.order = this.order.filter(k => k !== key);
this.order.push(key);
return this.map.get(key);
}
put(key, value) {
if (this.map.has(key)) {
this.order = this.order.filter(k => k !== key);
} else if (this.map.size >= this.capacity) {
const evict = this.order.shift();
this.map.delete(evict);
}
this.map.set(key, value);
this.order.push(key);
}
}
let c = new LRUCache(2);
c.put(1, 10);
c.put(2, 20);
console.log("Get 1: " + c.get(1));
c.put(3, 30);
console.log("Get 2: " + c.get(2));
console.log("Get 3: " + c.get(3));
console.log("Miss 9: " + c.get(9));
c.put(1, 11);
console.log("Update 1: " + c.get(1));
c.put(4, 40);
console.log("Evicted 3: " + c.get(3));
console.log("Kept 1: " + c.get(1));
console.log("Kept 4: " + c.get(4));
let s = new LRUCache(1);
s.put(1, 100);
s.put(2, 200);
console.log("Small 1: " + s.get(1));
console.log("Small 2: " + s.get(2));
Everything above the line let c = new LRUCache(2); is the class. The rest is the lesson's test code, which prints ten lines:
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
Language details
- Lines such as
capacity;andmap = new Map();in the class body are class fields. Each instance gets its ownMapand its own array, because the initialisers run once pernew. filterreturns a new array, so the result must be assigned back tothis.order. Callingthis.order.filter(...)alone changes nothing.shift()removes and returns the first element, and on an empty array it returnsundefined.- A
Mapcompares keys by identity for objects and by value for numbers, so1and"1"are different keys. The test code only uses numbers. getreturns-1for a miss, so a stored value of-1would look like a miss. The lesson stores non-negative values only.
Tracing the state
Printing order after each call on a cache of capacity 2 shows how the two structures move together:
put(1, 10) -> order: [1], map size: 1
put(2, 20) -> order: [1,2], map size: 2
10
get(1) -> order: [2,1], map size: 2
put(3, 30) -> order: [1,3], map size: 2
-1
get(2) -> order: [1,3], map size: 2
put(1, 11) -> order: [3,1], map size: 2
After get(1), key 1 moved behind key 2. So put(3, 30) evicted key 2, the front of order. The miss on key 2 left order alone, and updating key 1 moved it to the end without evicting anything.
Complexity
Each get and put runs filter over order, which holds at most capacity keys, so an operation takes O(capacity) time. The Map operations are constant time on average, and shift() on an array moves the remaining elements, which is also linear in the worst case. Space is O(capacity): the map and the array each hold at most that many keys.
Edge cases and common mistakes
- Forgetting that a hit is a use. If
getdoesn't move the key, the wrong entry is evicted. In the example, key 2 is evicted only because key 1 was just read. - Evicting on an update. A full cache must not drop anything when the key is already present, which is why the update case comes first in the
ifchain. - Capacity 1. Every new key evicts the previous one, as the last two test lines show.
- Capacity 0. The class has no special case for it. With
new LRUCache(0),put(1, 5)evicts nothing useful (the emptyordergivesundefined) and still stores the key, soget(1)returns 5. The lesson doesn't test this case. - Letting the structures drift apart. Update
mapandordertogether on every path.
