380. Insert Delete GetRandom O(1)
Asked at 34Bloomberg84Apple65Amazon60Meta51Google46Microsoft39Axon97Citadel87Yandex72DE Shaw58Affirm100Pocket Gems100Grammarly96Yelp94X94Peloton94Quora91Okta89SoFi86Docusign82LinkedIn76Uber76IXL72Pure Storage67Zeta64Palo Alto Networks59TikTok58Coupang58Snowflake54Cisco45Nvidia39Roblox37DoorDash36Oracle35
Problem
Design RandomizedSet with insert(val) and remove(val) (each returns whether the set changed) and getRandom() (a uniformly random current element, never called on an empty set), all in O(1) average time.
Example: insert(1) → true, remove(2) → false, insert(2) → true, getRandom() → 1 or 2, remove(1) → true, getRandom() → 2
Values live in an array (O(1) random pick); a map stores each value's index. To delete, move the last element into the hole and pop the end.
vals [5, 8, 2, 9] idx {5:0, 8:1, 2:2, 9:3}
remove 8: move 9 into slot 1 -> [5, 9, 2] idx {5:0, 9:1, 2:2}
Complexity: O(1) average per operation.
class RandomizedSet:
def __init__(self):
self.vals, self.idx = [], {}
def insert(self, val: int) -> bool:
if val in self.idx:
return False
self.idx[val] = len(self.vals)
self.vals.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.idx:
return False
i, last = self.idx.pop(val), self.vals.pop()
if i < len(self.vals): # removed element wasn't the last one
self.vals[i] = last
self.idx[last] = i
return True
def getRandom(self) -> int:
return random.choice(self.vals)
rs = RandomizedSet()
assert rs.insert(1) and not rs.remove(2) and rs.insert(2)
assert rs.getRandom() in (1, 2)
assert rs.remove(1) and not rs.insert(2) and rs.getRandom() == 2
class RandomizedSet {
private final List<Integer> vals = new ArrayList<>();
private final Map<Integer, Integer> idx = new HashMap<>();
private final Random rnd = new Random();
public boolean insert(int val) {
if (idx.containsKey(val)) return false;
idx.put(val, vals.size());
vals.add(val);
return true;
}
public boolean remove(int val) {
Integer i = idx.remove(val);
if (i == null) return false;
int last = vals.remove(vals.size() - 1);
if (i < vals.size()) { vals.set(i, last); idx.put(last, i); }
return true;
}
public int getRandom() { return vals.get(rnd.nextInt(vals.size())); }
}
type RandomizedSet struct {
vals []int
idx map[int]int // value -> position in vals
}
func Constructor() RandomizedSet {
return RandomizedSet{idx: map[int]int{}}
}
func (this *RandomizedSet) Insert(val int) bool {
if _, ok := this.idx[val]; ok {
return false
}
this.idx[val] = len(this.vals)
this.vals = append(this.vals, val)
return true
}
func (this *RandomizedSet) Remove(val int) bool {
i, ok := this.idx[val]
if !ok {
return false
}
last := this.vals[len(this.vals)-1] // move the last value into the hole: O(1)
this.vals[i] = last
this.idx[last] = i
this.vals = this.vals[:len(this.vals)-1]
delete(this.idx, val)
return true
}
func (this *RandomizedSet) GetRandom() int {
return this.vals[rand.Intn(len(this.vals))]
}