MFU Cache Implementation - Problem
Implement a Most Frequently Used (MFU) Cache data structure that supports the following operations:
get(key): Get the value of the key if it exists in the cache, otherwise return -1put(key, value): Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the most frequently used item before inserting a new item
The cache should track the frequency of access for each key. When multiple keys have the same highest frequency, remove the least recently used among them.
Both get and put operations must run in O(1) average time complexity.
Input & Output
Example 1 — Basic Operations
$
Input:
capacity = 2, operations = [["put",1,10],["put",2,20],["get",1],["put",3,30],["get",2]]
›
Output:
[10,-1]
💡 Note:
Put (1,10), put (2,20), get 1 returns 10 (freq becomes 2). Put (3,30) evicts key 2 (freq 1 < freq 2). Get 2 returns -1 (not found).
Example 2 — Frequency Ties
$
Input:
capacity = 2, operations = [["put",1,10],["put",2,20],["get",1],["get",2],["put",3,30]]
›
Output:
[10,20]
💡 Note:
Both keys have freq 2 after gets. When putting (3,30), evict key 1 (inserted earlier than key 2, so less recently used among ties).
Example 3 — Single Capacity
$
Input:
capacity = 1, operations = [["put",1,10],["get",1],["put",2,20],["get",1],["get",2]]
›
Output:
[10,-1,20]
💡 Note:
Get 1 increases its frequency to 2. Put (2,20) cannot evict key 1 (freq 2 > freq 1 of new key), so key 1 stays. Wait, this is MFU so we evict the MORE frequent - key 1 gets evicted. Get 1 returns -1, get 2 returns 20.
Constraints
- 0 ≤ capacity ≤ 104
- 1 ≤ key, value ≤ 105
- At most 2 × 105 calls to get and put
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code