Taro Logo

LFU Cache

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+23
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
Linked ListsArraysDynamic Programming

Design and implement a data structure for a Least Frequently Used (LFU) cache.

Implement the LFUCache class:

  • LFUCache(int capacity) Initializes the object with the capacity of the data structure.
  • int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.
  • void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.

To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.

When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.

The functions get and put must each run in O(1) average time complexity.

Example 1:

Input
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]

Explanation
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1);   // cache=[1,_], cnt(1)=1
lfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1);      // return 1
                 // cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
                 // cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2);      // return -1 (not found)
lfu.get(3);      // return 3
                 // cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
                 // cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1);      // return -1 (not found)
lfu.get(3);      // return 3
                 // cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4);      // return 4
                 // cache=[4,3], cnt(4)=2, cnt(3)=3

Constraints:

  • 1 <= capacity <= 104
  • 0 <= key <= 105
  • 0 <= value <= 109
  • At most 2 * 105 calls will be made to get and put.
 

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned by the `get` operation if the requested key does not exist in the cache?
  2. What constitutes a 'use' of an item—does a `get` operation count as a use that increases the frequency, or does only `put` count?
  3. If an existing key is updated via the `put` operation, should its frequency count be incremented, or does it stay the same?
  4. What is the expected time complexity for both the `get` and `put` operations?
  5. How should the cache behave if initialized with a capacity of zero?

Brute Force Solution

Approach

Imagine you have a storage box with limited capacity and you need to keep track of items and how often they are used. The brute force approach relies on simply keeping a master list of everything stored along with a tally for every single time an item is requested.

Here's how the algorithm would work step-by-step:

  1. When someone asks for an item, search through the entire master list to find it and hand it back.
  2. Every time an item is successfully found, increase its personal usage tally by one.
  3. If someone wants to add a new item and the storage box is completely full, scan the entire master list to find the item with the lowest usage tally.
  4. If there is a tie and multiple items share the lowest usage tally, look at when they were last touched and pick the oldest one.
  5. Remove that least-used item entirely from the master list to make space.
  6. Finally, place the new item into the now-available space in the master list with a starting usage tally of one.

Code Implementation

class LFUCache:
    def __init__(self, capacity: int):
        self.maximum_capacity = capacity
        self.master_storage_list = []

    def get(self, target_key: int) -> int:
        for item_record in self.master_storage_list:
            if item_record["key"] == target_key:
                item_record["usage_tally"] += 1
                item_record["last_access_time"] = self._get_next_timestamp()
                return item_record["value"]
        return -1

    def put(self, target_key: int, target_value: int) -> int:
        if self.maximum_capacity <= 0:
            return

        for item_record in self.master_storage_list:
            if item_record["key"] == target_key:
                item_record["value"] = target_value
                item_record["usage_tally"] += 1
                item_record["last_access_time"] = self._get_next_timestamp()
                return

        # Check capacity to evict the least frequently used item before adding a new one
        if len(self.master_storage_list) >= self.maximum_capacity:
            self.master_storage_list.sort(key=lambda record: (record["usage_tally"], record["last_access_time"]))
            self.master_storage_list.pop(0)

        new_record = {
            "key": target_key,
            "value": target_value,
            "usage_tally": 1,
            "last_access_time": self._get_next_timestamp()
        }
        self.master_storage_list.append(new_record)

    def _get_next_timestamp(self) -> int:
        if not hasattr(self, "global_time_counter"):
            self.global_time_counter = 0
        self.global_time_counter += 1
        return self.global_time_counter

Big(O) Analysis

Time Complexity
O(n) – For each operation like get or put in the brute force master list, we must potentially scan through all n stored items to locate the requested key or find the least frequently used item. When the capacity is reached, evicting the item with the lowest usage tally and oldest timestamp requires inspecting every single one of the n elements. This linear scan across the entire collection for every cache interaction drives the cost to scale directly with the number of stored items. Consequently, the total operations scale linearly with n, resulting in a runtime complexity of O(n).
Space Complexity
O(N) – To implement the LFU cache according to the plain English description, we utilize auxiliary data structures consisting of a master hash map and usage tracking lists that store up to N items simultaneously. As the cache capacity and total number of stored elements N increase, the extra memory required grows directly in proportion to N. Specifically, every stored item requires entries in the master tracking list and frequency tallies, which consume linear auxiliary space relative to the number of elements. Thus, the total extra memory used by these tracking structures simplifies in Big O notation to O(N).

Optimal Solution

Approach

To build a lightning-fast Least Frequently Used cache, we organize our items into neat groups based on how many times they have been accessed. By linking these frequency groups together and using a quick shortcut to find items instantly, we ensure that adding, finding, and removing items always happens in constant time.

Here's how the algorithm would work step-by-step:

  1. Imagine our storage as a vertical stack of shelves, where each shelf holds items that share the exact same usage count.
  2. Keep a direct map that points us straight to the exact location of any item we are looking for, so we never have to search blindly.
  3. When we ask for an item, look up its location, fetch it, and immediately bump its usage count up by one.
  4. Move that item from its current shelf to the shelf directly above it, which represents the next higher usage count.
  5. If a shelf becomes completely empty because we moved its last item away, remove that shelf entirely to keep our storage clean.
  6. When we need to add a new item and our storage is completely full, go straight to the bottom shelf representing the lowest usage count.
  7. Look at the very first item on that bottom shelf, which is the least frequently used, and throw it away to make room for the new arrival.
  8. Place any brand new item onto the shelf that represents a usage count of one, and reset any tracking for how recently it was touched.

Code Implementation

from collections import defaultdict, OrderedDict

class LFUCache:
    def __init__(self, cache_capacity: int):
        self.maximum_capacity = cache_capacity
        self.minimum_frequency = 0
        self.key_to_value_map = {}
        self.key_to_frequency_map = {}
        self.frequency_to_nodes_map = defaultdict(OrderedDict)

    def get(self, target_key: int) -> int:
        if target_key not in self.key_to_value_map:
            return -1
            
        # Increment frequency and relocate the item to the next higher shelf
        current_frequency = self.key_to_frequency_map[target_key]
        self.key_to_frequency_map[target_key] = current_frequency + 1
        
        self.frequency_to_nodes_map[current_frequency].pop(target_key)
        self.frequency_to_nodes_map[current_frequency + 1][target_key] = None
        
        if not self.frequency_to_nodes_map[current_frequency] and self.minimum_frequency == current_frequency:
            self.minimum_frequency += 1
            
        return self.key_to_value_map[target_key]

    def put(self, target_key: int, target_value: int) -> None:
        if self.maximum_capacity <= 0:
            return
            
        if target_key in self.key_to_value_map:
            self.key_to_value_map[target_key] = target_value
            self.get(target_key)
            return
            
        # Evict the least frequently used item from the bottom shelf if cache is full
        if len(self.key_to_value_map) >= self.maximum_capacity:
            evict_key, _ = self.frequency_to_nodes_map[self.minimum_frequency].popitem(last=False)
            del self.key_to_value_map[evict_key]
            del self.key_to_frequency_map[evict_key]
            
        # Place new items onto the shelf representing a usage count of one
        self.key_to_value_map[target_key] = target_value
        self.key_to_frequency_map[target_key] = 1
        self.frequency_to_nodes_map[1][target_key] = None
        self.minimum_frequency = 1

Big(O) Analysis

Time Complexity
O(1) – Every operation in our LFU cache, including looking up an item, updating its frequency, moving it between frequency shelves, and evicting the least frequently used item from the bottom shelf, relies on direct hash map navigation and constant time pointer manipulations. Because we never search blindly and all shelf adjustments take a strictly bounded number of steps regardless of the total items stored, the execution time remains completely constant. This direct retrieval and structural update process requires a constant number of operations, which simplifies to O(1).
Space Complexity
O(N) – The auxiliary space is driven by the direct hash map pointing to item locations and the grouped shelves tracking usage frequencies, where N represents the total number of items currently stored in the cache. Each item requires constant extra space inside the hash map and doubly linked frequency lists. As N grows to the maximum capacity of the cache, the total memory consumed by these tracking structures scales proportionally. Thus, the overall auxiliary space complexity simplifies to Big O of N.

Edge Cases

Cache capacity is initialized to zero
How to Handle:
Any put operation should immediately fail or evict since no items can be stored.
Getting or putting a key when the cache is empty
How to Handle:
Get operations return minus one and put operations simply insert the new item without eviction.
Updating an existing key using the put method
How to Handle:
The value is updated and the key's frequency counter is incremented as if it was accessed.
Tie-breaking when multiple keys share the minimum frequency
How to Handle:
A doubly linked list for each frequency bucket naturally evicts the least recently used item first.
Accessing a key that does not exist in the cache during a get operation
How to Handle:
The method simply returns minus one without modifying the cache state.
Handling a high volume of sequential operations on a single key
How to Handle:
Frequency tracking scales in constant time using hash maps combined with frequency doubly linked lists.
Inserting keys with negative integers or zero as valid values
How to Handle:
Hash maps and node structures treat keys and values uniformly regardless of their sign or magnitude.
0/75 completed