Design LFU Cache

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-09

Problem Statement

Designing and implementing a Least Frequently Used (LFU) Cache system that supports fast get and put operations while maintaining cache capacity. The cache must evict the least frequently used item when capacity is full. If multiple items have the same frequency, the least recently used (LRU) among them should be evicted.


🔶 Functional Requirements


1.put(key, value)
•Insert or update the value for a given key.
•If the cache reaches its capacity, evict the LFU item.
•If multiple LFU items exist, evict the least recently used one.
2.get(key)
•Retrieve the value of the key if it exists in the cache.
•If not present, return -1.
•On access, increase the usage frequency of the item.
3.Eviction Policy
•Evict item with lowest frequency count.
•Resolve ties using least recently used (LRU) strategy.


🔶 Non-Functional Requirements


•Time Complexity:
•get() and put() operations should run in O(1) on average.
•Space Efficiency:
•Should only store up to capacity elements.
•Thread Safety (Optional Extension):
•Ensure cache is thread-safe for concurrent get and put calls.


🔶 Constraints


•The capacity of the cache is fixed and > 0.
•Keys and values are integers (for simplicity).
•Frequency count must update on both get and put.


🔶 Example Use Case

1 2Input: capacity = 2 3put(1, 1) // Cache = {1=1}, freq(1)=1 4put(2, 2) // Cache = {1=1, 2=2}, freq(1)=1, freq(2)=1 5get(1) // returns 1, freq(1)=2 6put(3, 3) // Evicts key=2 (LFU: freq=1), Cache = {1=1, 3=3} 7get(2) // returns -1 (not found) 8get(3) // returns 3, freq(3)=2 9put(4, 4) // Evicts key=1 (LFU & LRU), Cache = {3=3, 4=4}


👉 In short:

"Design a class LFUCache with APIs get(key) and put(key, value) that implements a Least Frequently Used eviction policy with O(1) average complexity."

Solution

Comments