progress

~/problems / Linked lists / LRU / LFU cache

LFU Cache

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

hard ~40 min

Build a class LFUCache that evicts the least frequently used key, breaking ties by evicting the least recently used key among those with the lowest use count.

  • LFUCache(capacity); capacity may be 0, in which case nothing is ever stored.
  • get(key) returns the value or -1 if absent. A successful get increments the key's use count and makes it the most recent.
  • put(key, value): if the key exists, overwrite the value, increment its count and make it the most recent. Otherwise, if the cache is full, evict first (lowest count, then oldest last-use), then insert the new key with a use count of 1.
c = LFUCache(2)
c.put(1, 10)      # counts: 1 -> 1
c.put(2, 20)      # counts: 1 -> 1, 2 -> 1
c.get(1)          # 10   counts: 1 -> 2, 2 -> 1
c.put(3, 30)      # full: evict key 2 (lowest count); 3 -> 1
c.get(2)          # -1
c.get(3)          # 30   counts: 1 -> 2, 3 -> 2
c.put(4, 40)      # keys 1 and 3 tie at 2; key 1 was used longer ago, so evict it
c.get(1)          # -1

⭐ Bonus: scanning all keys for the minimum count on each eviction still passes; a speed test (capacity 10,000, 100,000 operations) earns a star if every operation is O(1).

Show hint

Group keys by their use count, keeping each group in recency order, and remember which count is currently the smallest. Think about how that smallest count can change after a get, a put of an existing key, and a put of a new key.

Topic: LRU / LFU cache. Hash map + doubly linked list for O(1) get/put.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc