Insert Delete GetRandom O(1) (LeetCode 380): Solution and Explanation

Medium
Array
Hash Table
Math
Design
Randomized

Design a RandomizedSet that supports insert, remove and getRandom, each in average O(1) time. getRandom must return every stored value with equal probability.

Intuition

No single structure does all three jobs. A hash set inserts and removes in O(1) but has no way to pick a uniformly random element without walking it. An array picks a random index in O(1) but removing from the middle shifts everything after it.

Combine them. Keep the values in an array for random access, and keep a hash map from each value to its index so any value can be found in O(1).

The only slow part left is removing from the middle of the array. The order of a set does not matter, so there is no need to shift. Copy the last value into the hole, update that value's index in the map, and pop the tail. Popping the end of an array is O(1).

Approach: Array + hash map, swap with last

  1. Keep vals, an array of the stored values, and pos, a map from each value to its index in vals.
  2. insert(val): if val is in pos, return false. Otherwise set pos[val] = len(vals), append val, and return true.
  3. remove(val): if val is not in pos, return false. Otherwise let i = pos[val] and last = vals[-1]. Set vals[i] = last and pos[last] = i, pop the tail, delete pos[val], and return true.
  4. getRandom(): return vals[random index].

Step-by-step example

insert 10, 20, 30, 40, then remove(20), remove(10), insert(50)
  1. After four inserts, vals = [10, 20, 30, 40] and pos = {10: 0, 20: 1, 30: 2, 40: 3}.
  2. remove(20): pos[20] = 1. The last value is 40, so copy it into index 1 and set pos[40] = 1. Pop the tail and delete 20. Now vals = [10, 40, 30].
  3. remove(10): pos[10] = 0. The last value is 30, so it moves to index 0 and pos[30] = 0. After the pop, vals = [30, 40].
  4. insert(50) appends at index 2. Every call returned true, and no element was ever shifted.

Code: Python, Java, C++

1import random
2
3class RandomizedSet:
4    def __init__(self):
5        self.vals = []
6        self.pos = {}
7
8    def insert(self, val: int) -> bool:
9        if val in self.pos:
10            return False
11        self.pos[val] = len(self.vals)
12        self.vals.append(val)
13        return True
14
15    def remove(self, val: int) -> bool:
16        if val not in self.pos:
17            return False
18        i = self.pos[val]
19        last = self.vals[-1]
20        self.vals[i] = last
21        self.pos[last] = i
22        self.vals.pop()
23        del self.pos[val]
24        return True
25
26    def getRandom(self) -> int:
27        return random.choice(self.vals)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1) average per operation

Each operation does a constant number of hash map lookups and writes plus array access at an index or at the end.

Space

O(n)

The array and the map each hold one entry per stored value.

Other approaches

Hash set only (time O(n) for getRandom, space O(n))

Insert and remove are O(1), but getRandom has to copy or walk the set to reach a random position, which is O(n) per call.

Array only (time O(n) for insert and remove, space O(n))

getRandom is O(1), but checking membership and removing both need a linear scan and a shift.

Common mistakes

  • Deleting pos[val] before updating pos[last]. When val is the last value itself, the order matters: write pos[last] = i first, then delete pos[val], or the stale entry survives.
  • Forgetting to update the moved value's index, which leaves the map pointing at a slot that was popped.
  • Calling list.remove(val) in Python or splice in JavaScript, which shifts elements and makes remove O(n).
  • In Java, calling vals.remove(i) with an Integer object instead of an int index removes by value, not by position.

Frequently asked questions

Why move the last element instead of deleting in place?

Deleting from the middle of an array shifts every later element, which is O(n). A set has no order to preserve, so overwriting the hole with the last element and popping the end keeps remove at O(1).

Does this still work when the removed value is the last one?

Yes. The last value is copied onto itself, its index is written back unchanged, and then the tail is popped and the key deleted. The order of those writes is what makes this case safe.

How do the Codemia tests check a random function?

They only call getRandom when the set holds exactly one element, so the correct answer is that element. A real uniform pick still passes, because with one element every pick gives the same value.

What is the time complexity of each operation?

O(1) on average. Hash map operations are average O(1), and the array is only read by index or changed at its end.