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 - 12 * 105 calls will be made to insert, remove, and getRandom.getRandom is called.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 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:
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]
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:
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)| Case | How to Handle |
|---|---|
| Removing an element when the data structure is empty | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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. |