#381

Insert Delete GetRandom O(1) - Duplicates allowed

Hard
ArrayHash TableMathDesignRandomizedHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1) on average for all operations
Space
O(1)
O(n)
💡

Intuition

Time O(1) on average for all operationsSpace O(n)

In the optimal approach, we use a combination of a list and a hash map. The list allows us to store elements and access them randomly, while the hash map keeps track of the indices of each element for efficient insertions and removals.

⚙️

Algorithm

3 steps
  1. 1Step 1: For insert, add the value to the list and update the hash map with the index of the new value.
  2. 2Step 2: For remove, find the index of the value in the hash map, swap it with the last element in the list, and remove the last element. Update the hash map accordingly.
  3. 3Step 3: For getRandom, simply return a random element from the list.
solution.py30 lines
1import random
2from collections import defaultdict
3
4class RandomizedCollection:
5    def __init__(self):
6        self.collection = []
7        self.index_map = defaultdict(set)
8
9    def insert(self, val):
10        self.collection.append(val)
11        self.index_map[val].add(len(self.collection) - 1)
12        return len(self.index_map[val]) == 1
13
14    def remove(self, val):
15        if val not in self.index_map or not self.index_map[val]:
16            return False
17        # Get an index of the element to remove
18        remove_idx = self.index_map[val].pop()
19        last_element = self.collection[-1]
20        self.collection[remove_idx] = last_element
21
22        # Update index_map for the last element
23        if self.index_map[last_element]:
24            self.index_map[last_element].remove(len(self.collection) - 1)
25            self.index_map[last_element].add(remove_idx)
26        self.collection.pop()
27        return True
28
29    def getRandom(self):
30        return random.choice(self.collection)

Complexity note: The use of a list allows O(1) access for random elements, while the hash map allows O(1) average time complexity for insertions and removals by keeping track of indices.

  • 1Using a hash map allows for efficient index tracking.
  • 2Swapping elements during removal avoids shifting elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.