Algo-Sim › Low-Level Design
Insert Delete GetRandom O(1)
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
An array for uniform random picks plus a value → index map; remove swaps the last value into the hole so nothing shifts.
Problem
Design a set of integers with insert(val) and remove(val), which return whether the set changed, and getRandom(), which returns one of the current values, each with the same probability. Every call must run in average O(1) time.
Constraints
- -2³¹ ≤ val ≤ 2³¹ − 1
- At most 2 · 10⁵ calls
- getRandom is only called on a non-empty set
- Every call is average O(1)
Edge cases to test
- Remove the last element (no swap needed)
- Insert a value already present:
false getRandomwith one element
Follow-up questions
- What if duplicates are allowed?
- Map each value to a set of indices; remove swaps any one index with the last (LC 381).
- Why swap with the last element?
- Removing from the middle of an array shifts everything; swapping with the end keeps remove O(1).
Solution
Java
class RandomizedSet {
private final List<Integer> nums = new ArrayList<>();
private final Map<Integer, Integer> index = new HashMap<>();
private final Random rand = new Random();
public boolean insert(int val) {
if (index.containsKey(val)) return false;
index.put(val, nums.size());
nums.add(val);
return true;
}
public boolean remove(int val) {
if (!index.containsKey(val)) return false;
int at = index.get(val), last = nums.get(nums.size() - 1);
nums.set(at, last);
index.put(last, at);
nums.remove(nums.size() - 1);
index.remove(val);
return true;
}
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}Python
import random
class RandomizedSet:
def __init__(self):
self.nums, self.index = [], {}
def insert(self, val):
if val in self.index: return False
self.index[val] = len(self.nums)
self.nums.append(val)
return True
def remove(self, val):
if val not in self.index: return False
at, last = self.index[val], self.nums[-1]
self.nums[at], self.index[last] = last, at
self.nums.pop()
del self.index[val]
return True
def getRandom(self):
return random.choice(self.nums)C++
#include <bits/stdc++.h>
using namespace std;
class RandomizedSet {
vector<int> nums;
unordered_map<int, int> index;
public:
bool insert(int val) {
if (index.count(val)) return false;
index[val] = nums.size();
nums.push_back(val);
return true;
}
bool remove(int val) {
if (!index.count(val)) return false;
int at = index[val], last = nums.back();
nums[at] = last;
index[last] = at;
nums.pop_back();
index.erase(val);
return true;
}
int getRandom() {
return nums[rand() % nums.size()];
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)