LFU Cache
The key idea
Problem
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
- LFUCache(int capacity) initializes the object with the capacity of the data structure.
- int get(int key) gets the value of the key if the key exists in the cache. Otherwise, returns -1.
- void put(int key, int value) updates the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e. two or more keys with the same frequency), the least recently used key would be invalidated.
To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. The use counter for a key is incremented by 1 either when it is inserted by put or when it is read by get. When a key is removed, its use counter is reset to 0.
The functions get and put must each run in O(1) average time complexity.
Constraints
1 <= capacity <= 10^40 <= key <= 10^50 <= value <= 10^9- At most
2 * 10^5calls will be made togetandput.
Examples
Complexity
Time: O(1) Space: O(capacity)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Design problems
- Binary Search Tree IteratorMEDIUM
- Design Circular QueueMEDIUM
- Design HashMapEASY
- Design HashSetEASY
- Design TwitterMEDIUM
- Detect SquaresMEDIUM
- Encode and Decode StringsMEDIUM
- Implement Queue using StacksEASY
- Implement Stack using QueuesEASY
- Insert Delete GetRandom O(1)MEDIUM
- LRU CacheMEDIUM
- Maximum Frequency StackHARD