#460

LFU Cache

Hard Frequency buckets of LinkedHashSets

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a cache with get and put in O(1). When full, evict the key used least often; among ties, evict the least recently used one.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: evict the least frequently used key; break ties by least recently used.

Why this works: group keys by use count, each group in insertion order (LinkedHashSet). Track the smallest count so eviction is O(1).

Example: capacity 2: put 1, put 2, get 1, put 3

counts: 1→2, 2→1put 3 evicts key 2 (lowest count)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting that minCount can only increase by touching keys and resets to 1 on every new insert.

Solve on LeetCode ↗
Complexity
  • Time: O(1) average per operation.
  • Space: O(capacity).
Topic: Linked List
🎬 Episodes 40–45: video coming soon