A cache with a size limit needs an eviction policy: when it's full and something new arrives, which entry gets thrown out? Least-Recently-Used is the workhorse answer — evict whatever hasn't been touched for the longest. It's behind HTTP caches, database buffer pools, and image caches, and it's a perennial interview question because doing it in O(1) forces you to combine a hash map with an ordering structure.
Implement lruCache(capacity) returning { get, put, size }, where every access marks a key as most-recently-used and inserts past capacity evict the least-recently-used.
function lruCache(capacity) {
return { get, put, size };
}
const c = lruCache(2);
c.put('a', 1);
c.put('b', 2);
c.get('a'); // 1 — 'a' is now most-recently-used
c.put('c', 3); // capacity 2 exceeded -> evict 'b' (the LRU)
c.get('b'); // undefined
c.get('c'); // 3
get hit and a put that updates an existing key both make that key most-recently-used.size past capacity, remove the least-recently-used entry (not the oldest-inserted, if it was used since).Map keeps insertion order, so its first key is the LRU and deleting-then-re-inserting a key moves it to the most-recently-used end.get returns undefined; store falsy values (0, '') faithfully.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.