C++
LFU Cache
STL
Cache Implementation
Programming

How to implement LFU cache using STL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Least Frequently Used (LFU) cache is a type of cache eviction algorithm opposite to Least Recently Used (LRU). In LFU caching, the item with the lowest frequency of access is removed first when the storage limit is exceeded. Such a mechanism is crucial in scenarios where it's necessary to ensure that items with higher access frequency are retained. In C++, the Standard Template Library (STL) provides various containers and algorithms that can help efficiently implement an LFU cache.

Understanding the LFU Cache Mechanism

An LFU Cache should offer the following operations:

  1. Get(key): Returns the value of the key if the key exists in the cache. Otherwise, returns -1.
  2. Put(key, value): Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the cache capacity, evict the least frequently used key.

Key Components Required

To implement LFU cache using STL, we need:

  • A hash map to store key-value pairs.
  • A hash map to store frequency counts.
  • A hash map of lists to maintain keys with the same frequency.

Implementation Steps

Let's design the LFU Cache leveraging STL containers:

Step 1: Data Structures

To keep track of our data, we'll primarily need:

  • A map `cache` to store key-value pairs.
  • A map `key_freq` to track the frequency of each key.
  • A map `freq_list` to maintain keys with the same frequency in a list.
    • The primary map `cache` maintains the key, its value, and the frequency of access.
    • `key_freq` tracks the current access frequency of each key.
    • `freq_list` maintains keys in lists where the keys have the same frequency, enabling removal from the least used list.
    • `get(key)`: Checks the existence of the key. If present, it updates the frequency, moves the key to the new frequency bucket, and returns the value.
    • `put(key, value)`: Inserts a key-value pair, evicts the least frequently used key if needed, and updates the frequency tracking structures.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.