LFU implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-12-25

Problem Statement

Design and implement an LFU (Least Frequently Used) Cache system. The cache should efficiently store key-value pairs, automatically evicting the least frequently used entries when capacity is reached. If multiple keys have the same frequency, the least recently used (LRU) among them should be evicted first.


Functional Requirements (FR)


Cache Operations


•get(key): Return the value associated with the key if present, else return -1.
•put(key, value): Insert a key-value pair into the cache.
•If the cache is full, evict the LFU entry.
•If multiple entries share the same frequency, evict the LRU among them.


Frequency Tracking


•Each time a key is accessed (via get or put), its frequency count should be incremented.


Capacity Constraints


•The cache should have a fixed capacity set at initialization.
•If capacity is 0, all operations should be no-ops.


Non-Functional Requirements (NFR)


Time Complexity:


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


Space Efficiency: Cache should not use unnecessary extra memory.


•Thread Safety (Optional): Support multithreaded access with locks.


Core Entities / Classes


LFUCache


•Attributes:
•capacity
•minFrequency
•keyToNodeMap → maps key → Node
•freqToDLLMap → maps frequency → DoublyLinkedList
•Methods:
•get(key)
•put(key, value)


Node


•Attributes:
•key
•value
•frequency
•Represents a cache entry.


DoublyLinkedList


•Attributes:
•head, tail (dummy nodes for easy insertion/removal)
•Methods:
•addNode(node)
•removeNode(node)
•removeLast() → remove least recently used node in that frequency list


Key Relationships


•LFUCache → Node: Each cache entry is represented as a Node.
•LFUCache → DoublyLinkedList: Each frequency has its own DLL to track order of usage.
•Node belongs to one frequency list at a time.


Example Flow


•Initialize cache with capacity 2.
•put(1, 1) → cache = {1=1}
•put(2, 2) → cache = {1=1, 2=2}
•get(1) → returns 1, increases freq of 1
•put(3, 3) → cache is full, evicts key 2 (LFU), adds {3=3}
•Final state: {1=1, 3=3}


✅ This is the LLD problem statement for LFU cache implementation.

Solution

Comments