Taro Logo

All O`one Data Structure

#3 Most AskedHard
1 view
Topics:
StringsGreedy AlgorithmsLinked Lists

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 <= 10
  • key consists of lowercase English letters.
  • It is guaranteed that for each call to dec, key is existing in the data structure.
  • At most 5 * 104 calls will be made to inc, dec, getMaxKey, and getMinKey.

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 `getMaxKey()` and `getMinKey()` return if the data structure is currently empty?
  2. If multiple keys share the exact same maximum or minimum frequency, does it matter which one of them is returned?
  3. Can we assume that `dec()` will only be called on keys that already exist in the data structure, or do we need to handle decreasing the count of a non-existent key?
  4. What is the maximum length of the string keys, and what character set do they belong to?
  5. When a key's count drops to 0 after a `dec()` operation, should it be completely removed from the data structure?

Brute Force Solution

Approach

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:

  1. Whenever a new item is added, just throw it onto a giant pile along with all the other items you have gathered so far.
  2. If an item is used again, search through your entire pile to find all copies of it and update their usage counts.
  3. When someone asks for the item with the highest usage, scan through every single item in your pile, compare their usage counts, and pick the one with the biggest number.
  4. When someone asks for the item with the lowest usage, scan through every single item in your pile again, compare their usage counts, and pick the one with the smallest number.
  5. Whenever an item's usage drops to zero, search the pile to remove all traces of it so you do not accidentally count it anymore.

Code Implementation

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']

Big(O) Analysis

Time Complexity
O(n) – For each of n elements in the pile, we must search through the entire collection to find matching items, update counts, or remove unused traces. When someone asks for the highest or lowest usage, we scan every single item in the pile to compare their counts. This requires traversing up to n elements for each of the insertion, update, retrieval, and deletion operations. These sequential full-pile scans approximate roughly n operations per request, which simplifies to a linear time complexity of O(n).
Space Complexity
O(N) – To implement the All O`one Data Structure efficiently, we utilize auxiliary hash maps and doubly linked lists to track keys and their frequencies. Specifically, we store every unique key in a hash map pointing to its node, and maintain bucket nodes for each frequency count to achieve constant time operations. As the number of unique items, denoted as N, increases, these internal data structures scale linearly to hold every key and frequency node. Therefore, the total extra memory consumed by our tracking structures is directly proportional to N, resulting in a linear space complexity.

Optimal Solution

Approach

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:

  1. Maintain a fast lookup directory that instantly connects any item name to its current count and its specific place in our collection.
  2. Create a linked chain of buckets where each bucket holds a specific count number and all the items that currently share that exact count.
  3. Link these buckets in order from the smallest count to the largest count so that neighboring counts are always right next to each other.
  4. When an item is used or added, look up its current bucket, remove it from that bucket, and place it into the next higher or lower bucket depending on whether its count went up or down.
  5. If moving an item causes a bucket to become completely empty, simply remove that bucket from the chain and connect its neighbors directly to each other.
  6. If an item needs a count that does not currently have a bucket, create a new bucket for that count and insert it neatly between the existing neighboring buckets.
  7. To instantly find the item with the highest count, just look at the very last bucket in the chain and grab any item inside it.
  8. To instantly find the item with the lowest count, just look at the very first bucket in the chain and grab any item inside it.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(1) – Every operation in the All One Data Structure, including inc, dec, getMaxKey, and getMinKey, relies entirely on hash map lookups and constant-time pointer updates within a doubly linked list of buckets. Because we directly access the item via the fast lookup directory and manipulate adjacent bucket nodes without searching through all stored items, the execution time remains completely independent of the total number of items n. Therefore, across all methods, the total operations require a constant number of steps, which simplifies to O(1) time complexity.
Space Complexity
O(N) – The auxiliary space is driven by the fast lookup directory hash map and the linked chain of buckets, where N represents the total number of unique keys currently stored in the data structure. The hash map stores N key-value pairs pointing to node locations, while the doubly linked list contains at most N unique count buckets with individual sets of keys. Therefore, the total extra memory scales linearly with the number of unique items managed by the system.

Edge Cases

Operations on a key that does not yet exist in the data structure during a decrement
How to Handle:
The system should safely ignore the request or ensure safe removal without throwing lookup exceptions.
Decrementing a key whose frequency drops to zero
How to Handle:
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
How to Handle:
Return an empty string since no valid keys exist to represent the extreme frequencies.
Multiple keys sharing the exact same maximum or minimum frequency
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The internal pointers for head and tail must correctly update their references without getting corrupted or orphaned.
0/6 completed