LRU Cache

Data StructuresCachingDesign

Build an LRUCache class that holds a fixed number of entries and, once full, throws away whichever entry was used least recently.

  • new LRUCache(capacity) — how many entries fit before eviction starts.
  • get(key) — returns the value, or -1 if the key is not there. A successful get counts as a use.
  • put(key, value) — inserts or updates. Counts as a use either way. If this takes the cache past its capacity, evict the least recently used entry.

Both get and put must run in O(1) — no scanning the keys to find the oldest one.

Examples

Example 1
Input
const cache = new LRUCache(3);

cache.put('user:1', { name: 'Pratik' });
cache.put('user:2', { name: 'Rahul' });
cache.put('user:3', { name: 'Aman' });

cache.get('user:1');                     // { name: 'Pratik' }

cache.put('user:4', { name: 'Vikas' });  // over capacity

cache.get('user:2');
cache.get('user:1');
Output
-1
{ name: 'Pratik' }
Explanation
Reading user:1 made it recently used, so when user:4 arrived the least recently used entry was user:2 — and that is the one evicted.

Constraints

  • 1 <= capacity <= 1000
  • Keys are strings; values can be anything, including falsy values
  • get and put must both be O(1)

Notes

  • A read is a use. Forgetting that get refreshes recency is the single most common mistake here.
  • Storing a miss — even as -1 — quietly consumes capacity and evicts real entries early.
  • The test suite grades behaviour, not complexity. O(1) is still a requirement, and the Solution tab explains how to get it.

Hints

Read the full write-up for LRU Cache
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it