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 <= 1040 <= key <= 1050 <= value <= 1092 * 105 calls will be made to get and put.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:
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:
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_counterTo 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:
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| Case | How to Handle |
|---|---|
| Cache capacity is initialized to zero | Any put operation should immediately fail or evict since no items can be stored. |
| Getting or putting a key when the cache is empty | Get operations return minus one and put operations simply insert the new item without eviction. |
| Updating an existing key using the put method | 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 | 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 | The method simply returns minus one without modifying the cache state. |
| Handling a high volume of sequential operations on a single key | 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 | Hash maps and node structures treat keys and values uniformly regardless of their sign or magnitude. |