Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.
Implement the AllOne class:
AllOne() Initializes the object of the data structure.inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1.dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "".getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "".Note that each function must run in O(1) average time complexity.
Example 1:
Input ["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] [[], ["hello"], ["hello"], [], [], ["leet"], [], []] Output [null, null, null, "hello", "hello", null, "hello", "leet"] Explanation AllOne allOne = new AllOne(); allOne.inc("hello"); allOne.inc("hello"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "hello" allOne.inc("leet"); allOne.getMaxKey(); // return "hello" allOne.getMinKey(); // return "leet" Constraints:
1 <= key.length <= 10key consists of lowercase English letters.dec, key is existing in the data structure.5 * 104 calls will be made to inc, dec, getMaxKey, and getMinKey.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 need to keep track of a collection of items and know instantly which ones appear the most often or the least often whenever asked. The brute force approach relies on simply maintaining a plain list of everything and doing a complete search from scratch every single time a question is asked.
Here's how the algorithm would work step-by-step:
class AllOne:
def __init__(self):
self.storage_pile = []
def inc(self, key: str) -> None:
# We search the entire pile to update existing counts or add a new entry
found_match = False
for item_entry in self.storage_pile:
if item_entry['key'] == key:
item_entry['count'] += 1
found_match = True
break
if not found_match:
self.storage_pile.append({'key': key, 'count': 1})
def dec(self, key: str) -> None:
# We update the usage count and prepare to remove items that reach zero
for item_entry in self.storage_pile:
if item_entry['key'] == key:
item_entry['count'] -= 1
break
self.storage_pile = [entry for entry in self.storage_pile if entry['count'] > 0]
def getMaxKey(self) -> str:
# Scanning the entire pile is required to find the absolute maximum usage
if not self.storage_pile:
return ""
max_entry = max(self.storage_pile, key=lambda entry: entry['count'])
return max_entry['key']
def getMinKey(self) -> str:
# Scanning the entire pile is required to find the absolute minimum usage
if not self.storage_pile:
return ""
min_entry = min(self.storage_pile, key=lambda entry: entry['count'])
return min_entry['key']To manage items and their counts so we can instantly find the ones with the highest and lowest counts, we combine two powerful organization tools: a fast lookup directory and a chain of connected buckets. This clever combination lets us update counts and find our extremes in a fraction of a second, without having to search through everything.
Here's how the algorithm would work step-by-step:
class BucketNode:
def __init__(self, frequency_value):
self.frequency = frequency_value
self.key_collection = set()
self.next_bucket = None
self.previous_bucket = None
class AllOne:
def __init__(self):
self.key_to_bucket = {}
self.head_sentinel = BucketNode(0)
self.tail_sentinel = BucketNode(0)
self.head_sentinel.next_bucket = self.tail_sentinel
self.tail_sentinel.previous_bucket = self.head_sentinel
def inc(self, key_string: str) -> None:
# If key is absent, it starts at frequency 1; otherwise, it moves to the next bucket.
if key_string not in self.key_to_bucket:
current_bucket = self.head_sentinel
target_frequency = 1
else:
current_bucket = self.key_to_bucket[key_string]
target_frequency = current_bucket.frequency + 1
next_bucket_node = current_bucket.next_bucket
if next_bucket_node == self.tail_sentinel or next_bucket_node.frequency != target_frequency:
new_bucket = BucketNode(target_frequency)
new_bucket.previous_bucket = current_bucket
new_bucket.next_bucket = next_bucket_node
current_bucket.next_bucket = new_bucket
next_bucket_node.previous_bucket = new_bucket
target_bucket = new_bucket
else:
target_bucket = next_bucket_node
target_bucket.key_collection.add(key_string)
self.key_to_bucket[key_string] = target_bucket
if current_bucket != self.head_sentinel:
current_bucket.key_collection.remove(key_string)
if not current_bucket.key_collection:
self._remove_bucket_node(current_bucket)
def dec(self, key_string: str) -> None:
current_bucket = self.key_to_bucket[key_string]
target_frequency = current_bucket.frequency - 1
if target_frequency == 0:
del self.key_to_bucket[key_string]
else:
previous_bucket_node = current_bucket.previous_bucket
if previous_bucket_node == self.head_sentinel or previous_bucket_node.frequency != target_frequency:
new_bucket = BucketNode(target_frequency)
new_bucket.next_bucket = current_bucket
new_bucket.previous_bucket = previous_bucket_node
previous_bucket_node.next_bucket = new_bucket
current_bucket.previous_bucket = new_bucket
target_bucket = new_bucket
else:
target_bucket = previous_bucket_node
target_bucket.key_collection.add(key_string)
self.key_to_bucket[key_string] = target_bucket
current_bucket.key_collection.remove(key_string)
if not current_bucket.key_collection:
self._remove_bucket_node(current_bucket)
def getMaxKey(self) -> str:
# The highest frequency bucket is located right before the tail sentinel.
if self.tail_sentinel.previous_bucket == self.head_sentinel:
return ""
return next(iter(self.tail_sentinel.previous_bucket.key_collection))
def getMinKey(self) -> str:
# The lowest frequency bucket is located right after the head sentinel.
if self.head_sentinel.next_bucket == self.tail_sentinel:
return ""
return next(iter(self.head_sentinel.next_bucket.key_collection))
def _remove_bucket_node(self, bucket_node: BucketNode) -> None:
previous_node = bucket_node.previous_bucket
next_node = bucket_node.next_bucket
previous_node.next_bucket = next_node
next_node.previous_bucket = previous_node| Case | How to Handle |
|---|---|
| Operations on a key that does not yet exist in the data structure during a decrement | The system should safely ignore the request or ensure safe removal without throwing lookup exceptions. |
| Decrementing a key whose frequency drops to zero | The key must be completely removed from both the frequency mapping and the doubly linked list of counts. |
| Retrieving max or min keys when the data structure is completely empty | Return an empty string since no valid keys exist to represent the extreme frequencies. |
| Multiple keys sharing the exact same maximum or minimum frequency | Return any single valid key from the corresponding bucket as permitted by the problem statement. |
| Incrementing a brand new key that has never been inserted before | Initialize the key with a frequency of one and place it directly into the frequency one bucket. |
| A frequency bucket becoming completely empty after a key is incremented or decremented | Remove the corresponding node from the doubly linked list to maintain strictly contiguous frequency tracking in O(1) time. |
| Handling a large number of distinct keys and frequent updates | Use a combination of a hash map and a doubly linked list to ensure all operations strictly achieve O(1) time complexity. |
| Repeatedly incrementing and decrementing the same single key | The internal pointers for head and tail must correctly update their references without getting corrupted or orphaned. |