DEV Community

Jaspreet singh
Jaspreet singh

Posted on

Design a LFU ( Least Frequently Used ) Cache

Problem Statement

get()

put()
Enter fullscreen mode Exit fullscreen mode

Both operations must run in:

O(1)
Enter fullscreen mode Exit fullscreen mode

Brute Force Intuition

Maintain:

Key

Value

Frequency
Enter fullscreen mode Exit fullscreen mode

Whenever cache is full:

Find minimum frequency by scanning entire cache.

Remove that key.

Complexity

  • get → O(1)
  • put → O(N)

Moving Towards the Optimal Approach

Need fast access to:

Node

Frequency

Minimum Frequency
Enter fullscreen mode Exit fullscreen mode

Use:

HashMap<Key,Node>

HashMap<Frequency,DLL>

Minimum Frequency Variable
Enter fullscreen mode Exit fullscreen mode

Pattern Recognition

Cache

+

Frequency

=> Multiple Doubly Linked Lists
Enter fullscreen mode Exit fullscreen mode

Key Observation

Each frequency has its own DLL.

Example:

Freq 1

1 ⇄ 7 ⇄ 10
Enter fullscreen mode Exit fullscreen mode
Freq 2

5 ⇄ 9
Enter fullscreen mode Exit fullscreen mode

Whenever frequency increases:

Remove from old DLL

↓

Insert into next frequency DLL
Enter fullscreen mode Exit fullscreen mode

Operations

get()

Frequency++

Move Node
Enter fullscreen mode Exit fullscreen mode

put()

If exists:

Update Value

Increase Frequency
Enter fullscreen mode Exit fullscreen mode

Else:

If full:

Remove

Least Frequency

Least Recently Used
Enter fullscreen mode Exit fullscreen mode

Insert new node into:

Frequency = 1
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Operation Complexity
Get O(1)
Put O(1)

Interview One-Liner

Use a HashMap for node lookup, another HashMap for frequency-wise doubly linked lists, and maintain the minimum frequency for O(1) eviction.


Pattern Learned

Cache

+

Frequency

+

Recency

=> HashMap + Multiple DLLs
Enter fullscreen mode Exit fullscreen mode

Memory Trick

LRU

HashMap

+

One DLL

↓

Least Recently Used
Enter fullscreen mode Exit fullscreen mode
LFU

HashMap

+

Many DLLs

↓

Least Frequently Used
Enter fullscreen mode Exit fullscreen mode

Similar Problems

  • LRU Cache
  • LFU Cache
  • Design Browser History
  • All O(1) Data Structure
  • Insert Delete GetRandom O(1)

Top comments (0)