LRU Cache
HardDesign · Hash map + listO(1) get and put
The problem
Design a cache with a fixed capacity that supports get(key) and put(key, value) in O(1). When it is full, evict the least recently used entry.
Stuck? Open one hint
A map gives O(1) lookup but no order. A list gives order but O(n) lookup. What if every map value were a list node?
Show the worked solution
Combine the two structures: a hash map from key to node, and a doubly linked list ordered from most to least recently used.
get— find the node via the map, unlink it, move it to the front.put— insert at the front; if over capacity, drop the tail and remove that key from the map.
The doubly linked list is what makes unlinking O(1): you have the node, so you do not need to search for its neighbours.
This is the mobile-relevant one — image caches and Room's in-memory cache work exactly like this, and Android ships LruCache. Mention that, then still write it, because they want the structure.
class LRUCache(private val capacity: Int) {
private val map = LinkedHashMap<Int, Int>(capacity, 0.75f, true) // accessOrder = true
fun get(key: Int): Int = map[key] ?: -1
fun put(key: Int, value: Int) {
map[key] = value
if (map.size > capacity) {
val oldest = map.keys.iterator().next()
map.remove(oldest)
}
}
}
// In an interview, be ready to write the map + doubly linked list by hand too —
// LinkedHashMap with accessOrder is the production answer, not the teaching one.O(1) get and put
