LRU Cache
mediummapcachedata-structures
Asked at



Amazon, Cloudflare, Datadog, Google, Microsoft
Problem statement
Implement an LRUCache class. LRU means least recently used.
When the cache exceeds its capacity, it should evict the least recently used key.
API
const cache = new LRUCache(2);
cache.set('a', 1);
cache.set('b', 2);
cache.get('a'); // 1, now a is most recent
cache.set('c', 3); // evicts b
Requirements
get(key)returns the value or-1when missing.set(key, value)inserts or updates a key.- Both
getandsetshould update recency. - Evict the least recently used key when size exceeds capacity.
- Use
O(1)average operations.
Requirements & constraints
- Capacity must be positive.
- Missing values return -1.
- Average get/set should be O(1).
How to approach LRU Cache
The strategy an interviewer expects you to reach for.
Approach JavaScript Map preserves insertion order. We can use that order as recency order by deleting and re-inserting a key whenever it is accessed.
Premium
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.