Overview
Design a data structure for a Least Recently Used (LRU) cache. It should support:
get(key)— return the value or -1 if not foundput(key, value)— insert/update and evict the least recently used key if at capacity
Both operations must be O(1).
Constraints
1 <= capacity <= 30000 <= key, value <= 10,000
Examples
const c = new LRUCache(2); c.put(1, 1); c.put(2, 2); c.get(1); // => 1 c.put(3, 3); // evicts key 2 c.get(2); // => -1
Solution
Reveal solution
class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return -1;
const val = this.map.get(key);
this.map.delete(key);
this.map.set(key, val);
return val;
}
put(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.cap) {
this.map.delete(this.map.keys().next().value);
}
}
}JavaScript's Map maintains insertion order, so the first key is the LRU.
Resources
lru-cache.js
LRU Cache
mediumcodingAlgorithmsDesign
Overview
Design a data structure for a Least Recently Used (LRU) cache. It should support:
get(key)— return the value or -1 if not foundput(key, value)— insert/update and evict the least recently used key if at capacity
Both operations must be O(1).
Constraints
1 <= capacity <= 30000 <= key, value <= 10,000
Examples
const c = new LRUCache(2); c.put(1, 1); c.put(2, 2); c.get(1); // => 1 c.put(3, 3); // evicts key 2 c.get(2); // => -1
Solution
Reveal solution
class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return -1;
const val = this.map.get(key);
this.map.delete(key);
this.map.set(key, val);
return val;
}
put(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.cap) {
this.map.delete(this.map.keys().next().value);
}
}
}JavaScript's Map maintains insertion order, so the first key is the LRU.
Resources
NameTopicDifficulty
103 of 103 problems