AAlgoLoopSpaced repetition for LeetCode
HARDDesignLeetCode ↗

LFU Cache

The key idea

Group keys by their use frequency. Keep the keys at each frequency in least-recently-used order, and track the smallest live frequency. Eviction is then "take the LRU key in the smallest-frequency group" — an O(1) lookup instead of a scan.

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

Examples

Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] Output: [null, null, null, 1, null, -1, 3, null, -1, 3, 4]
Input: ["LFUCache", "put", "put", "get", "put", "get", "get"] [[2], [1, 10], [2, 20], [1], [3, 30], [2], [1]] Output: [null, null, null, 10, null, -1, 10]

Complexity

Time: O(1) Space: O(capacity)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems