hardSoftware EngineerTechnology
How would you implement an LRU cache with O(1) get and put?
Posted 18/04/2026
by Mehedy Hasan Ador
Question Details
"Implement LRU cache. Used in browser caching, DB buffer pools, CDN eviction."
Suggested Solution
HashMap + Doubly Linked List
class LRUCache<K, V> {
private map = new Map<K, Node<K,V>>();
constructor(private capacity: number) {}
get(key: K): V | null {
const node = this.map.get(key);
if (!node) return null;
this.moveToHead(node); // Mark recently used
return node.value;
}
put(key: K, value: V): void {
if (this.map.has(key)) { /* update + move to head */ return; }
const node = new Node(key, value);
this.map.set(key, node);
this.addToHead(node);
if (this.map.size > this.capacity) {
const lru = this.removeTail(); // Evict least recently used
this.map.delete(lru.key);
}
}
}
All operations O(1): HashMap for lookup, linked list for ordering.