LRU cache from scratch
Build the famous O(1) least-recently-used cache, then use it to speed up a slow function and measure the hit rate.
What you'll learn
- âCombining a hash map with a doubly linked list
- âO(1) get and put
- âCache hit and miss rates
What you'll build
- âget(key) and put(key, value) in O(1)
- âEvicts the least recently used item
- âHit/miss statistics
- âThread-safe version
Step-by-step guide
- 1
Understand the idea
The map finds a node in O(1); the list keeps usage order (most recent at the head, least recent at the tail).
- 2
Node and list
class Node { key, value, prev, next } with dummy head and tail nodes so you never check for null.
- 3
get
If the key is in the map, move its node to the head and return the value; else count a miss.
- 4
put
If present, update and move to head. Else create a node at the head; if size > capacity remove tail.prev and delete its key from the map.
- 5
Test
Write tests for capacity 1, updating existing keys, and eviction order.
- 6
Use it
Wrap a slow function (for example fetching a web page or a heavy calculation) and print hit rate and time saved.
- 7
Thread safety
Add a lock (synchronized in Java, std::mutex in C++) and explain the trade-off.
đ Make it stand out
- +Add time-based expiry (TTL)
- +Compare with LinkedHashMap / functools.lru_cache
- +Implement LFU cache