Utility functions · mid
LRU cache
An LRU cache keeps at most capacity entries and evicts the least recently used one; in JavaScript a Map does this in O(1) because it remembers insertion order — on get, delete and re-insert the key to mark it fresh, and on overflow delete map.keys().next().value, the oldest key.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Invariant: the Map's insertion order is the recency order, oldest first, newest last.
- get(k): if missing return -1 (or undefined); otherwise read the value, delete the key, set it again, and return the value.
- put(k, v): delete k if present, set it, and if size > capacity delete the oldest key: map.keys().next().value.
- Without Map ordering (or if the interviewer forbids it): a hash map from key to node plus a doubly linked list with head and tail sentinels; moving a node to the front is O(1).
- Edge cases: capacity 1; updating an existing key refreshes it; get of a missing key changes nothing.
- Extensions: a TTL per entry (store expiresAt and check on get), size limits in bytes, LFU, and an LRU-bounded promise memo (Microsoft).
- Uses: API response cache, image cache in a virtualised list, bounding a memoize cache, 'recently viewed' items.
- State the invariant out loud before coding. (The learner needed hints like 'Map stores the node'.)
The red pen
Common traps: mistake → fix
Mistake: An array with indexOf/splice
Fix: O(n) per operation.
Mistake: Forgetting to refresh the key on get.
Mistake: Evicting before checking whether the key already exists.
Easy to hard
Questions interviewers ask, easy to hard
- Implement an LRU cache with O(1) get and put.
- Why is a JavaScript Map enough? What does keys().next() return?
- Implement it with a doubly linked list plus a hash map.
- Add a TTL per entry.
- Where would you use an LRU cache in a frontend app?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.