LRU Cache

HardDesign Patterns30 min5 tests

Implement an LRU (Least Recently Used) Cache with a fixed capacity.

Requirements

  • get(key) — return the value if it exists, otherwise return -1. Mark as recently used.
  • put(key, value) — insert or update the value. If capacity is exceeded, evict the least recently used item.
  • Both operations should be O(1) time.

Example

const cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);    // 1
cache.put(3, 3); // evicts key 2
cache.get(2);    // -1
Hints (4)
  1. JavaScript Map maintains insertion order — the first key is the oldest.
  2. On get, delete and re-insert to move to the end.
  3. On put, check capacity and evict the first key from the Map if full.
  4. Use map.keys().next().value to get the least recently used key.

Topics

  • Design Patterns

Asked at

Google · Amazon · Meta · Microsoft

Join Us
blur