An interactive visualization of the LRU Cache design problem. Watch how a hash map and doubly linked list combine for O(1) get and put operations with least-recently-used eviction.
Hash Map Linked List LeetCode 146 โ MediumLRUCache class:LRUCache(int capacity) โ Initialize the cache with positive size capacity.int get(int key) โ Return the value of the key if it exists, otherwise return -1. This marks the key as recently used.void put(int key, int value) โ Update the value of the key if it exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity, evict the least recently used key.get and put must run in O(1) average time complexity.
class Node(var key: Int, var value: Int) { var prev: Node? = null var next: Node? = null}class LRUCache(private val cap: Int) { private val cache = HashMap<Int, Node>() // key -> node private val head = Node(0, 0) // dummy private val tail = Node(0, 0) // dummy init { head.next = tail; tail.prev = head } fun get(key: Int): Int { val node = cache[key] ?: return -1 remove(node) addToFront(node) // move to front return node.value } fun put(key: Int, value: Int) { cache[key]?.let { remove(it) } val node = Node(key, value) addToFront(node) cache[key] = node if (cache.size > cap) { val lru = tail.prev!! remove(lru) cache.remove(lru.key) } }}
The LRU Cache requires two properties: O(1) lookup and O(1) insertion/deletion/reordering. No single data structure provides both. A hash map gives O(1) lookup, and a doubly linked list gives O(1) insert/remove at any position (given a reference to the node). By combining them โ storing node references in the hash map โ we get O(1) for every operation.
cache maps keys to linked list nodes. A doubly linked list maintains the usage order, with most recently used near the head and least recently used near the tail.
Every operation involves a constant number of hash map lookups/insertions and linked list pointer updates.
The space is bounded by the cache capacity โ we store at most capacity nodes plus two dummy sentinels.