Problem overview
A cache holds a limited number of recent results. When it is full and a new key arrives, it must drop something. An LRU (Least Recently Used) cache drops the entry that was used longest ago. The lesson asks for a class LRUCache with integer keys and integer values, built from three fields: capacity (a number), map (a Map<number, number> from key to value) and order (a number[] of keys, least recently used first).
The class has two methods:
get(key)returns the stored value and marks the key as the most recently used. For a key that isn't stored it returns-1and changes nothing.put(key, value)stores the value and marks the key as the most recently used. Replacing the value of an existing key evicts nothing. A new key arriving in a full cache first evicts the least recently used key.
Take a cache of capacity 2. After put(1, 10) and put(2, 20), order is [1, 2]. Calling get(1) returns 10 and moves key 1 to the end, so order becomes [2, 1]. Now put(3, 30) finds the cache full and evicts the front key, 2, leaving order as [1, 3]. A later get(2) returns -1.
Approach: two structures, one invariant
Each structure does the job it is good at. The Map answers "is this key stored, and what is its value?" quickly. The array answers "which key is the oldest?" by position: the front is the least recently used key and the end is the most recently used one. Every use takes the key out of its place and pushes it at the end.
The one rule to protect is that map and order always contain the same keys. Whenever you add or remove a key in one, you do the same in the other.
This version searches the array on every use, which takes time proportional to the number of stored keys. That is fine for learning the behaviour. A cache that does every operation in constant time combines a hash map with a doubly linked list instead; this lesson builds the simpler array version.
Step by step
- Declare the class and its closing brace. Everything else goes inside.
- Add the three fields.
capacityis anumberthat the constructor fills in.mapstarts as an emptyMapandorderas an empty array, so a new cache is empty without any constructor code for them. - Write the constructor and save its argument in
this.capacity. - Start
getwith the miss case. If the map doesn't have the key, return-1immediately. A miss must not touchorder. - Move the key to the end. Rebuild
this.orderwithfilter, keeping every key except this one, thenpushthe key. The key is now the most recently used. - Return the value from the map.
- Start
putwith the update case. If the map already has the key, take it out oforderwith the samefilter. The size doesn't change, so nothing is evicted. - Add the eviction case as an
else if: the key is new andthis.map.sizeis already at leastthis.capacity. Remove the first key oforderwithshift(), and delete that key from the map too. Removing it from only one structure would break the rule above. - After the whole
ifchain, store the value in the map and push the key at the end oforder. This runs for everyput, new key or update, which is why it sits outside the branches.
The solution in TypeScript
class LRUCache {
capacity: number;
map: Map<number, number> = new Map();
order: number[] = [];
constructor(capacity: number) {
this.capacity = capacity;
}
get(key: number): number {
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: number, value: number): void {
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));
TypeScript details
- Field initializers.
map: Map<number, number> = new Map()declares the field's type and gives it a starting value in one line. The constructor only has to deal withcapacity. - The
!aftergetandshift().Map.getis typed as returningnumber | undefined, and so isshift(). The trailing!tells the compiler you know the value is there. It is only a type annotation: it is erased when the code compiles to JavaScript and checks nothing at run time. Here it is true, becausegetalready checkedhas(key)and an eviction only happens when the map holds entries. filterreturns a new array. That is why the result is assigned back tothis.order. Callingthis.order.filter(...)without the assignment would change nothing.Mapsize.this.map.sizeis a property, not a method, so there are no parentheses.
Complexity
With n keys stored, has, set and delete on the Map are constant time on average. The filter call visits every key, so get and an update in put take O(n) time. shift() also has to move the remaining items, so an eviction is O(n) as well. The space is O(capacity): the map and the array each hold at most that many keys.
Edge cases and common mistakes
- Reading a key must refresh it. In the example, key 2 is evicted because
get(1)made key 1 the more recent one. Skipping the move ingetwould evict key 1 instead. - Updating an existing key must not evict. If the size check ran before the
hascheck, a full cache would throw away an entry just to replace a value. Theif/else iforder avoids it. - Forgetting to delete from the map. Shifting the key out of
orderbut not out ofmapleaves a stale value thatgetkeeps returning, and the map grows past its capacity. - Duplicate keys in
order. Pushing a key without first removing its old position makes the array longer than the map and ruins the eviction order. - A miss changes nothing.
get(9)on a missing key returns-1and leavesorderas it was. - Capacity 0. The class assumes a capacity of at least 1. With capacity 0,
puton an empty cache has nothing to evict, soshift()givesundefinedand the entry is stored anyway. The lesson's tests use capacities 1 and 2.
Testing
Try these in the editor above. With capacity 1, put(1, 100) then put(2, 200) evicts key 1, so get(1) is -1 and get(2) is 200. With capacity 2, after put(1, 10), put(2, 20), get(1) and put(3, 30), get(2) is -1 while get(3) is 30.
