Taro Logo

Insert Delete GetRandom O(1)

#12 Most AskedMedium
0 views
Topics:
ArraysArraysDynamic Programming

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

Constraints:

  • -231 <= val <= 231 - 1
  • At most 2 * 105 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

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 data type are the values being inserted (e.g., standard 32-bit integers, strings, or objects), and what is the expected range of these values?
  2. How should the `insert` and `remove` operations behave if we attempt to insert a value that already exists or remove a value that is not present?
  3. Can we assume that `getRandom` will only be called when the data structure is guaranteed to be non-empty?
  4. Are duplicate values allowed to be stored in this data structure, or are we strictly implementing a set where all elements are unique?
  5. Do `insert` and `remove` need to be strictly $O(1)$ on average (amortized), or is a strict worst-case $O(1)$ required for every single operation?

Brute Force Solution

Approach

Imagine you have a magical box where you can put items, take them out, and occasionally close your eyes and blindly grab a random item. The brute force strategy involves keeping every single piece of paper with an item name written on it in a giant stack, and then flipping through or sorting through the entire stack whenever you need to check something or pick a random piece.

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

  1. Whenever someone hands you a new item, just toss its name onto the top of your giant stack of papers.
  2. When someone asks you to remove an item, search through every single paper in your stack from top to bottom until you find the matching name, and then throw that paper away.
  3. When someone asks if an item is already inside, look through every single paper in the stack from top to bottom to see if the name appears.
  4. When someone asks for a random item, close your eyes, reach into the stack, and grab a random paper, hoping you do not pull out a duplicate or a blank spot.
  5. If you pulled out a blank spot or a duplicate because you kept old papers around, repeat the random grab until you hold a valid paper.

Code Implementation

import random

class RandomizedSet:
    def __init__(self):
        self.stack_of_papers = []

    def insert(self, item_name):
        if item_name in self.stack_of_papers:
            return False
        # We add the item directly to the top of our stack since uniqueness must be checked first
        self.stack_of_papers.append(item_name)
        return True

    def remove(self, item_name):
        if item_name not in self.stack_of_papers:
            return False
        # We scan the entire stack sequentially to locate and remove the exact matching item
        self.stack_of_papers.remove(item_name)
        return True

    def getRandom(self):
        # We blindly pick a random index from the stack until we successfully grab a valid item
        while len(self.stack_of_papers) > 0:
            random_index = random.randint(0, len(self.stack_of_papers) - 1)
            return self.stack_of_papers[random_index]

Big(O) Analysis

Time Complexity
O(n) – For insertion, tossing the item onto the top of the stack takes constant time, but removal and containment checks require scanning through all n papers in the stack one by one. When asking for a random item, we may need to repeat our random grab through the stack of size n if we hit duplicate or blank spots. In the worst case, checking and removing elements requires inspecting up to n items sequentially. This linear search across the entire stack of size n drives the overall cost, simplifying to O(n).
Space Complexity
O(N) – The auxiliary space is driven by two data structures required to manage the items in the magical box. Specifically, we use a hash map to store each item name alongside its index, and a dynamic list (or stack of papers) to store the item names sequentially. As the total number of unique elements N grows, both the hash map and the dynamic list scale linearly to accommodate every inserted item. Therefore, the total extra memory consumed by these data structures is directly proportional to N, resulting in a linear space complexity.

Optimal Solution

Approach

To achieve instantaneous performance for adding, removing, and picking a random item, we combine two different organizational tools: a fast lookup directory and a dynamic collection. The secret trick to achieving instant deletion is swapping the target item with the very last item in the collection before throwing it away.

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

  1. Maintain two internal tools: a quick-reference notebook that remembers where each item is stored, and a straight line of items where things can be added or removed.
  2. When asked to insert a new item, first check the quick-reference notebook to see if it already exists. If it does not, place the new item at the very end of the straight line and update the notebook to remember its exact position.
  3. When asked to remove an item, check the notebook to find its location in the straight line. To avoid leaving an empty gap that takes too long to fix, look at whatever item is currently sitting at the very end of the straight line.
  4. Move that final item into the spot left vacant by the item you want to delete, and update the notebook to reflect this new position.
  5. Finally, remove the target item from the straight line and erase it from the notebook, which keeps everything tightly packed together without any gaps.
  6. When asked to pick a random item, simply reach blindly into the straight line of items and select one at random, knowing every item is equally likely to be chosen.
  7. Because every single one of these actions involves direct steps rather than searching through everything one by one, all operations happen instantaneously.

Code Implementation

import random

class RandomizedSet:
    def __init__(self):
        self.lookup_directory = {}
        self.item_collection = []

    def insert(self, target_item: int) -> bool:
        # Prevent duplicate entries to ensure set behavior and unique mapping.
        if target_item in self.lookup_directory:
            return False
            
        self.item_collection.append(target_item)
        self.lookup_directory[target_item] = len(self.item_collection) - 1
        return True

    def remove(self, target_item: int) -> bool:
        # Verify existence before attempting index lookups and swaps.
        if target_item not in self.lookup_directory:
            return False
            
        target_index = self.lookup_directory[target_item]
        last_item = self.item_collection[-1]
        
        self.item_collection[target_index] = last_item
        self.lookup_directory[last_item] = target_index
        
        self.item_collection.pop()
        del self.lookup_directory[target_item]
        return True

    def get_random(self) -> int:
        # Randomly choose an index directly in O(1) time without searching.
        return random.choice(self.item_collection)

Big(O) Analysis

Time Complexity
O(1) – For insertion and deletion, hash map lookups and dynamic array operations like appending or swapping with the last element and popping take constant time, regardless of the number of elements n. For random selection, accessing a dynamic array by a randomly generated index also takes constant time. Because all three operations avoid iterative searching and rely solely on direct index or key access, the cost per operation is strictly bounded and simplifies to O(1).
Space Complexity
O(N) – To satisfy the requirements, we maintain two primary auxiliary data structures: a dynamic list of items and a hash map serving as the quick-reference notebook. As elements are inserted, both the list and the hash map grow in direct proportion to the number of stored elements, denoted as N. The dynamic list stores each of the N items sequentially, while the hash map stores N key-value pairs mapping each item to its index. Therefore, the total extra memory consumed by these combined data structures scales linearly with the number of elements, resulting in an auxiliary space complexity of O(N).

Edge Cases

Removing an element when the data structure is empty
How to Handle:
The hash map lookup fails immediately, allowing the method to safely return false without throwing an error.
Inserting a duplicate element that already exists in the data structure
How to Handle:
The hash map detects the existing key and returns false to indicate the insertion did not occur.
Removing the very last element remaining in the data structure
How to Handle:
The swap-with-last optimization is bypassed because the target is already the last element, and it is simply popped from the list.
Calling getRandom when the data structure contains only a single element
How to Handle:
The random number generator restricts its bound to zero, consistently and correctly returning that single element.
Handling negative numbers, zero, and extreme integer boundary values
How to Handle:
The hash map and dynamic array store values as keys and indices natively, making them agnostic to the specific integer values.
Scaling up to maximum-sized inputs with millions of operations
How to Handle:
The combination of a hash map and a dynamic array ensures all operations maintain expected O(1) time complexity and amortized constant memory growth.
Ensuring a truly uniform probability distribution during getRandom calls
How to Handle:
Generating a random index within the exact current size of the dynamic array guarantees every stored element has an equal probability of selection.
Removing an element that is located at the very beginning of a large data structure
How to Handle:
The element is overwritten by swapping it with the last element in the array in O(1) time before updating its index in the hash map.
0/17 completed