Map plus ordered list: the LRU trick
Build constant-time get, put and evict-oldest.
Two jobs, two structures
An LRU cache must find a key fast and find the least recently used key fast. A map does the first; an ordered list does the second. Keep them in sync.
In JavaScript a Map remembers insertion order, so deleting and re-inserting a key moves it to the newest end, and the first key is the oldest.
get(key: string) {
if (!this.map.has(key)) return undefined;
const v = this.map.get(key)!;
this.map.delete(key);
this.map.set(key, v); // now the newest
return v;
}
In other languages
Use a hash map from key to a node in a doubly linked list. Moving a node to the front and removing the tail are both constant time.
Key takeaways
- Two fast operations often need two structures.
- Ordered map: delete then set to refresh.
- Elsewhere: hash map plus doubly linked list.
Hands-on coding exercise
A cache that holds at most `capacity` entries. When full, putting a new key removes the least recently used one. Reading a key counts as using it.
A Map remembers insertion order: delete and re-insert a key to move it to the end, and the first key is the oldest.
class LruCache {
constructor(private readonly capacity: number) {}
/** The value, or undefined */
get(key: string): number | undefined {
throw new Error("Not implemented");
}
put(key: string, value: number): void {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- Why does an array-based LRU cache fail the large hidden test?
- In a JavaScript Map, how do you mark a key as most recently used?