Least Frequently Used (LFU) Implementation

A Least Frequently Used (LFU) cache is a memory management strategy that removes the least frequently accessed items when the cache reaches capacity. Unlike LRU (Least Recently Used), LFU tracks how often each item is accessed and evicts items with the lowest usage count.

In an LFU cache, each item maintains a frequency counter that increments every time it's accessed. When eviction is needed, the item with the smallest frequency count is removed first.

How LFU Cache Works

The LFU algorithm follows these principles:

  • Frequency Tracking: Each cached item has an associated usage count
  • Eviction Policy: When cache is full, remove the item with lowest frequency
  • Tie Breaking: If multiple items have the same lowest frequency, remove the oldest one

Implementation Using Python Dictionary

Here's a complete LFU cache implementation using Python dictionaries for efficient lookup and storage ?

class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = {}  # Dictionary to store key-value pairs
        self.counts = {}  # Dictionary to store usage count of each key
        
    def get(self, key: int) -> int:
        if key in self.cache:
            # Increment the usage count when item is accessed
            self.counts[key] += 1
            return self.cache[key]
        else:
            return -1  # Key not found
    
    def put(self, key: int, value: int) -> None:
        if self.capacity == 0:
            return
        
        if key in self.cache:
            # Update existing item and increment count
            self.cache[key] = value
            self.counts[key] += 1
        else:
            if len(self.cache) >= self.capacity:
                # Find and evict least frequently used item
                min_count = min(self.counts.values())
                lfu_keys = [k for k, count in self.counts.items() if count == min_count]
                # Remove first item found (FIFO for ties)
                evict_key = lfu_keys[0]
                del self.cache[evict_key]
                del self.counts[evict_key]
            
            # Add new item with initial count of 1
            self.cache[key] = value
            self.counts[key] = 1

# Example usage
cache = LFUCache(2)  # Create cache with capacity 2

cache.put(1, 1)  # Cache: {1:1}, Counts: {1:1}
cache.put(2, 2)  # Cache: {1:1, 2:2}, Counts: {1:1, 2:1}

print(cache.get(1))  # Access key 1, increments count to 2
cache.put(3, 3)      # Evicts key 2 (least frequent), adds key 3
print(cache.get(2))  # Key 2 was evicted
print(cache.get(3))  # Access key 3, increments count to 2
print(cache.get(1))  # Access key 1, increments count to 3
1
-1
3
1

Method Breakdown

__init__ Method

Initializes the cache with two dictionaries: cache stores key-value pairs, while counts tracks usage frequency for each key.

get Method

Retrieves a value by key. If the key exists, increments its usage count and returns the value. Returns -1 if the key is not found.

put Method

Adds or updates a key-value pair. For existing keys, updates the value and increments the count. For new keys, adds the pair with count 1. If capacity is exceeded, evicts the least frequently used item.

Time and Space Complexity

Operation Time Complexity Space Complexity
get() O(1) O(1)
put() O(n) worst case O(1)
Overall O(n) for eviction O(capacity)

Use Cases

LFU caches are ideal for scenarios where:

  • Web Caching: Storing frequently requested web pages
  • Database Caching: Keeping popular query results in memory
  • CPU Caches: Hardware-level instruction and data caching
  • Application Caches: Storing computed results or expensive operations

Conclusion

LFU cache efficiently manages limited memory by prioritizing frequently accessed items. While this implementation has O(n) eviction time, it provides a solid foundation for understanding LFU principles and can be optimized further using advanced data structures for production use.

Updated on: 2026-03-27T06:05:21+05:30

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements