380. Insert Delete GetRandom O(1)
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core challenge is to design a data structure that supports insert, remove, and getRandom operations, all in average O(1) time.
Solution
Insert Delete GetRandom O(1) in Python
import random
class RandomizedSet:
def __init__(self):
# List to store elements for O(1) random access.
self.nums = []
# Dictionary to map values to their indices in the list.
self.val_to_index = {}
def insert(self, val: int) -> bool:
# If value is already in the set, return False.
if val in self.val_to_index:
return False
# Add value to the end of the list.
self.nums.append(val)
# Store the value's index.
self.val_to_index[val] = len(self.nums) - 1
return True
def remove(self, val: int) -> bool:
# If value is not in the set, return False.
if val not in self.val_to_index:
return False
# Get the index of the element to remove.
index_to_remove = self.val_to_index[val]
# Get the last element in the list.
last_element = self.nums[-1]
# Move the last element to the position of the element to remove.
self.nums[index_to_remove] = last_element
# Update the index of the moved element in the dictionary.
self.val_to_index[last_element] = index_to_remove
# Remove the last element (which is now a duplicate of the moved element, or the original val).
self.nums.pop()
# Remove the original value from the dictionary.
del self.val_to_index[val]
return True
def getRandom(self) -> int:
# random.choice is an efficient and clean way to get a random element from a list.
return random.choice(self.nums)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
Insert Delete GetRandom O(1) in Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
class RandomizedSet {
// List to store the elements for O(1) random access.
private List<Integer> nums;
// Map to store value to its index in the list for O(1) lookup.
private Map<Integer, Integer> valToIndex;
// Random object for generating random indices.
private Random rand;
public RandomizedSet() {
nums = new ArrayList<>();
valToIndex = new HashMap<>();
rand = new Random();
}
public boolean insert(int val) {
// If the value is already present, return false.
if (valToIndex.containsKey(val)) {
return false;
}
// Add the value to the end of the list.
nums.add(val);
// Map the value to its new index (the last position).
valToIndex.put(val, nums.size() - 1);
return true;
}
public boolean remove(int val) {
// If the value is not present, return false.
if (!valToIndex.containsKey(val)) {
return false;
}
// Get the index of the element to remove.
int indexToRemove = valToIndex.get(val);
// Get the last element in the list.
int lastElement = nums.get(nums.size() - 1);
// Move the last element to the position of the element to remove.
nums.set(indexToRemove, lastElement);
// Update the map for the moved element.
valToIndex.put(lastElement, indexToRemove);
// Remove the last element from the list.
nums.remove(nums.size() - 1);
// Remove the original value from the map.
valToIndex.remove(val);
return true;
}
public int getRandom() {
// Get a random index from 0 to nums.size() - 1.
int randomIndex = rand.nextInt(nums.size());
// Return the element at the random index.
return nums.get(randomIndex);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
Insert Delete GetRandom O(1) in C++
class RandomizedSet {
private:
// Vector to store the elements. Allows for O(1) random access.
std::vector<int> nums;
// Map to store the value and its index in the vector.
// Allows for O(1) average time lookup of values.
std::unordered_map<int, int> val_to_index;
public:
RandomizedSet() {
// For deterministic behavior in tests, you might seed rand(), but it's often not necessary
// for LeetCode's testing environment as they handle it.
// srand(time(NULL));
}
bool insert(int val) {
// If the value is already in the map, it's in the set.
if (val_to_index.count(val)) {
return false;
}
// Add the value to the end of the vector.
nums.push_back(val);
// Store the value and its index (which is the last position) in the map.
val_to_index[val] = nums.size() - 1;
return true;
}
bool remove(int val) {
// If the value is not in the map, it's not in the set.
if (!val_to_index.count(val)) {
return false;
}
// The core trick for O(1) removal from a vector:
// 1. Get the index of the element to remove.
int index_to_remove = val_to_index[val];
// 2. Get the last element in the vector.
int last_element = nums.back();
// 3. Move the last element to the position of the element to remove.
nums[index_to_remove] = last_element;
// 4. Update the map with the new index of the last element.
val_to_index[last_element] = index_to_remove;
// 5. Remove the last element from the vector (which is now a duplicate of the moved element, or the original val).
nums.pop_back();
// 6. Remove the original value from the map.
val_to_index.erase(val);
return true;
}
int getRandom() {
// Generate a random index within the bounds of the vector's size.
// `rand() % nums.size()` is a simple way to do this.
return nums[rand() % nums.size()];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
Insert Delete GetRandom O(1) in TypeScript
class RandomizedSet {
// Array to store elements for O(1) random access.
private nums: number[];
// Map to store value to its index in the array for O(1) lookup.
private valToIndex: Map<number, number>;
constructor() {
this.nums = [];
this.valToIndex = new Map();
}
insert(val: number): boolean {
// If value is already present, return false.
if (this.valToIndex.has(val)) {
return false;
}
// Add value to the end of the array.
this.nums.push(val);
// Map the value to its new index (the last position).
this.valToIndex.set(val, this.nums.length - 1);
return true;
}
remove(val: number): boolean {
// If value is not present, return false.
if (!this.valToIndex.has(val)) {
return false;
}
// Get the index of the element to remove. The '!' asserts it's not undefined.
const indexToRemove = this.valToIndex.get(val)!;
// Get the last element in the array.
const lastElement = this.nums[this.nums.length - 1];
// Move the last element to the position of the element to remove.
this.nums[indexToRemove] = lastElement;
// Update the map for the moved element.
this.valToIndex.set(lastElement, indexToRemove);
// Remove the last element from the array.
this.nums.pop();
// Remove the original value from the map.
this.valToIndex.delete(val);
return true;
}
getRandom(): number {
// Generate a random index from 0 to nums.length - 1.
const randomIndex = Math.floor(Math.random() * this.nums.length);
// Return the element at the random index.
return this.nums[randomIndex];
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.