#380

Insert Delete GetRandom O(1)

Medium
ArrayHash TableMathDesignRandomizedHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(n)
O(n)
💡

Intuition

Time O(1)Space O(n)

The optimal solution uses a combination of a hash map and an array to achieve O(1) time complexity for all operations. The hash map allows for quick lookups, while the array enables efficient random access.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a hash map to store the value and its index in the array.
  2. 2Step 2: Create an array to store the elements.
  3. 3Step 3: For insert, check if the value exists in the hash map; if not, add it to the array and hash map and return true; otherwise, return false.
  4. 4Step 4: For remove, find the index of the value in the array using the hash map, swap it with the last element, remove the last element, and update the hash map accordingly.
  5. 5Step 5: For getRandom, return a random element from the array.
solution.py23 lines
1import random
2class RandomizedSet:
3    def __init__(self):
4        self.map = {}
5        self.nums = []
6    def insert(self, val):
7        if val not in self.map:
8            self.map[val] = len(self.nums)
9            self.nums.append(val)
10            return True
11        return False
12    def remove(self, val):
13        if val in self.map:
14            last_element = self.nums[-1]
15            idx = self.map[val]
16            self.nums[idx] = last_element
17            self.map[last_element] = idx
18            self.nums.pop()
19            del self.map[val]
20            return True
21        return False
22    def getRandom(self):
23        return random.choice(self.nums)

Complexity note: The time complexity is O(1) for all operations because the hash map allows for constant time lookups, and the array allows for constant time access to elements.

  • 1Using a hash map allows for O(1) average time complexity for lookups.
  • 2Swapping elements during removal helps maintain O(1) complexity.

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