Insert Delete GetRandom O(1)

Hash map of value to index plus a dense vector — swap-with-last for O(1) delete, uniform random by index.

Medium
Time O(1) per op Space O(n)
LeetCode
3 min read
design hash-map array

Problem#

Implement a set supporting insert(val), remove(val), and getRandom() — each in average O(1). getRandom must return any current element with uniform probability.

Examples#

  • insert(1); insert(2); getRandom()1 or 2 with 1/2 each.
  • remove(1); getRandom()2.

Constraints#

  • -2^31 <= val <= 2^31 - 1, up to 2 * 10^5 ops.

Approach#

Maintain a vector<int> vals (dense), and unordered_map<int,int> pos from value to its index in vals. To delete, swap the target with the last element, pop the last, update the moved element’s position.

Solution#

RandomizedSet
class RandomizedSet {
vector<int> vals;
unordered_map<int,int> pos;
public:
bool insert(int val) {
if (pos.count(val)) return false;
pos[val] = vals.size();
vals.push_back(val);
return true;
}
bool remove(int val) {
auto it = pos.find(val);
if (it == pos.end()) return false;
int idx = it->second, last = vals.back();
vals[idx] = last;
pos[last] = idx;
vals.pop_back();
pos.erase(it);
return true;
}
int getRandom() {
return vals[rand() % vals.size()];
}
};

Editorial#

The dense vector is essential for uniform-random O(1) selection. Naive deletion would be O(n); the swap-with-last trick keeps the vector compact without preserving order — which we don’t need.

Complexity#

  • Time: O(1) average per op.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.