LLD Guide · Module 2: Problem prep · Lesson 02.03

Prep: LRU Cache

Two structures, one recency order, O(1) everything, and one method that must not touch the order.

By Cruscible Engineering · Published

Every LRU cache is a map plus an order. The bugs come from the moments they disagree.

This lesson prepares you for Build an LRU Cache. It doesn't solve it.

1. What the LRU cache contract asks for

A cache with a fixed capacity. When it's full and a new key arrives, the least recently used entry goes. get and put count as use; containsKey doesn't.

MethodReturns / does
init(capacity)sets the capacity (≥ 1); called once, first
get(key)the value, or null; marks the key as most recently used
put(key, value)inserts or updates; marks it most recently used; evicts the LRU entry first if full and the key is new
remove(key)true if the key existed
size()current entries, never above capacity
containsKey(key)true if present, without changing the order

All of get, put and remove must be O(1) amortised, at 50,000 operations a second with P99 under 1 ms, with capacities up to 10,000.

Figure: The brief's own example, step by step: what get, put and containsKey do to the order

2. Lessons to read before the LRU cache

3. LRU cache design decisions to make first

  1. What gives you O(1) lookup, and what gives you O(1) "move to front" and "remove oldest"? Name both structures and what each holds.
  2. What happens on put of a key that already exists? Does it evict anything? What happens to its position?
  3. Which order of steps keeps the map and the order consistent? Especially in put with an eviction.
  4. Where does the provided KV store fit? The brief says to use it for the underlying data. What do you keep in the KV store, and what in your own structure?
  5. What is your locking plan? Note that get writes: it changes the order. Does a read-write lock still help?

4. LRU cache pitfalls

⚠️ Trap: containsKey must not promote the key. If your structure reorders on every access (for example a LinkedHashMap in access order), containsKey must avoid that path.

⚠️ Trap: updating an existing key never evicts, even when the cache is full.

⚠️ Trap: get changes the order, so it is a write as far as locking is concerned. Two concurrent get calls under a read lock can corrupt the order.

Before you submit

Further reading

After you've tried it

Submit first. The full walkthrough of one solution: Building an LRU Cache with O(1) Operations.

Open the problem