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 -1
  • put(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
INPUTALGORITHMRESULTput(1,10)put(2,20)get(1)put(3,30)get(2)Capacity: 2Cache Size: 21Track Frequencies2Update on Access3Find Max Frequency4Evict MFU ItemFrequency Mapkey1: freq=2key2: freq=1key3: freq=1get(1) → 10get(2) → -1Evicted key1 (most frequent)Key2 was removed from cacheFinal Output: [10, -1]Key Insight:MFU Cache evicts the MOST frequently used items (opposite of LRU), using hash mapsand frequency groups for O(1) operations with LRU tie-breaking.TutorialsPoint - MFU Cache Implementation | Hash Map + Frequency Groups
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen