Problem Statement
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement get and put operations, both running in average time complexity.
Intuition
We need fast key lookup (hash map) and fast ordering updates (doubly linked list). The most recently used item goes to the head; the least recently used is at the tail, ready for eviction.
Approach
- Use a
Mapwhich preserves insertion order in JavaScript. - On
get, delete and re-insert the key to move it to the end (most recent). - On
put, delete the key if it exists, then insert it. If capacity is exceeded, delete the first (oldest) key.
Solution
TypeScript
class LRUCache {
private capacity: number;
private cache: Map<number, number>;
constructor(capacity: number) {
this.capacity = capacity;
this.cache = new Map();
}
get(key: number): number {
if (!this.cache.has(key)) return -1;
const val = this.cache.get(key)!;
this.cache.delete(key);
this.cache.set(key, val);
return val;
}
put(key: number, value: number): void {
this.cache.delete(key);
this.cache.set(key, value);
if (this.cache.size > this.capacity) {
const oldest = this.cache.keys().next().value!;
this.cache.delete(oldest);
}
}
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Map operations are amortized constant time | |
| Space | Where k is the cache capacity |