LRU cache
Hard TimeO(1) per op SpaceO(capacity)
Build a cache holding a fixed capacity of entries which, when full, throws away whichever key has gone longest without being touched. Reading counts as touching, not only writing, and writing an existing key updates it rather than adding a second copy. Both get and put have to run in constant time, which rules out scanning for the oldest entry, and a missing key reads as -1.
Examples
Example 1
- Input
- demo()
- Output
- 1 and 2 are stored; reading 1 leaves 2 the oldest, so storing 3 evicts it and
[100,-1,300]get(2)is-1.
Example 2
- Input
- makeLRUCache(2).get(9)
- Output
- Nothing has been stored yet, so key 9 is missing and reads as
-1-1.
The Code
function makeLRUCache(capacity) {
const map = new Map();
return {
get(key) {
if (!map.has(key)) return -1;
const value = map.get(key);
map.delete(key);
map.set(key, value);
return value;
},
put(key, value) {
if (map.has(key)) {
map.delete(key);
} else if (map.size >= capacity) {
const oldest = map.keys().next().value;
map.delete(oldest);
}
map.set(key, value);
return map.size;
}
};
}
function demo() {
const cache = makeLRUCache(2);
cache.put(1, 100);
cache.put(2, 200);
const first = cache.get(1);
cache.put(3, 300);
return [first, cache.get(2), cache.get(3)];
}
demo();Done
More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Detect a cycle A slow and a fast pointer must meet if the list loops.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Merge two lists A dummy head removes every special case for the first node.
- Remove nth from end Open an n-node gap between two pointers, then walk them together.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.