Skip to the page

Frontend-flavoured problems · mid

LRU and LFU cache design

An LRU cache evicts the least recently used key in O(1): in JavaScript a Map already keeps insertion order, so get is delete-then-set and eviction removes map.keys().next().value; without that, use a hash map plus a doubly linked list.

The notes

What you must know

  • Map version: get(k): if missing return -1; v = map.get(k); map.delete(k); map.set(k, v); return v. put(k, v): delete if present, set, and if size > capacity delete map.keys().next().value.
  • Classic version: Map key → node; doubly linked list with head (most recent) and tail (least recent) sentinels; move-to-front on access; remove tail on overflow. Say why the list must be doubly linked (O(1) removal from the middle).
  • put on an existing key updates the value AND recency.
  • LFU: key → {value, freq}; freq → ordered set of keys (a Map of Sets keeps LRU order per frequency); minFreq pointer; on overflow evict the least recently used key with minFreq; a new key resets minFreq to 1.
  • Frontend variants: memoise an async function with size limit and TTL (cache the promise to dedupe in-flight calls, delete it on rejection), image caches, autocomplete result caches.
  • TTL: store expiresAt and check on read (lazy expiry); inject now() for testability.

The red pen

Common traps: mistake → fix

  • Mistake: Use an array with indexOf/splice for recency

    Fix: O(n) per operation.

  • Mistake: map.set on an existing key moves it to the end

    Fix: it does not; delete first.

  • Mistake: Cache only resolved values in a promise memo

    Fix: two calls in flight both hit the network.

  • Mistake: A singly linked list is enough

    Fix: removing a node from the middle needs its previous node.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement an LRU cache with O(1) get and put.
  2. Now without relying on Map order.
  3. Add a TTL per entry.
  4. Implement LFU; how do you break ties?
  5. Memoise an API call with a size limit; what about failed calls?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview