🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

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.

Intermediate⏱ 4–6 hoursđŸĒœ 7 stepsJava or C++ or PythonHashMapDoubly linked list

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. 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. 2

    Node and list

    class Node { key, value, prev, next } with dummy head and tail nodes so you never check for null.

  3. 3

    get

    If the key is in the map, move its node to the head and return the value; else count a miss.

  4. 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. 5

    Test

    Write tests for capacity 1, updating existing keys, and eviction order.

  6. 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. 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