Insert Delete GetRandom O(1) solution explained

Insert Delete GetRandom O(1) asks for a set that adds, removes and returns a uniformly random member, each in constant average time. A hash set alone cannot pick a random member quickly, and an array alone cannot find a value quickly, so you use both: an array of the values and a map from each value to its position. To delete, move the last value into the hole and pop the end, which keeps the array packed so a random index is always a valid pick.

By Published 7 min read

The task, restated

Build a collection of distinct integers with three operations. insert(val) adds val and returns true, or returns false if val is already present. remove(val) deletes val and returns true, or returns false if it was not there. get_random() returns one of the current members, each with the same probability, and is only called when the collection is not empty. All three must run in O(1) on average, and the calls can come in any order and any number.

A made-up session
CallReturnsitems arrayIndex map
insert(4)true[4]4:0
insert(9)true[4, 9]4:0, 9:1
insert(4)false[4, 9]unchanged
remove(7)false[4, 9]unchanged
insert(2)true[4, 9, 2]4:0, 9:1, 2:2
get_random()4, 9 or 2, each a third of the time
remove(4)true[2, 9]2:0, 9:1; 2 moved into the hole
remove(9)true[2]2:0; 9 was already last
A made-up session. Scroll sideways on a small screen.

Note that the array order changes after a removal. That is allowed: the structure is a set, and only membership and uniform picks are promised. Ask anyway, since an interviewer who wants insertion order preserved is asking a different question.

What it tests

The problem is a lesson in combining data structures, each covering the other's weakness. Interviewers grade the idea of swap-with-last deletion, the exact order of updates in remove, and whether you can argue that get_random is uniform. Follow-ups are common:

  • Allow duplicates. Map each value to a set of positions. get_random then picks each copy uniformly, so a value with three copies is three times as likely. Removal takes any one position from the set and does the same swap.
  • Weighted picks instead of uniform ones. That is Random Pick With Weight, which uses prefix sums.
  • Pick a random key from a hash map you cannot change. Without an auxiliary array, the honest answer is O(n) or a sampling trick with retries.
  • Thread safety. All three methods touch both structures, so they need a shared lock to stay consistent.

Slow designs

With only a hash set, insert and remove are O(1), but get_random has to turn the set into a list or walk to a random position, O(n) per call. With only an array, get_random is O(1), but checking membership and removing are O(n) scans. Either is a fine first sentence. The code below uses the set-only version, which doubles as a reference for testing.

import random

class SetOnly:
    def __init__(self):
        self.members = set()

    def insert(self, val):
        if val in self.members:
            return False
        self.members.add(val)
        return True

    def remove(self, val):
        if val not in self.members:
            return False
        self.members.remove(val)
        return True

    def get_random(self):
        return random.choice(list(self.members))
Python: O(n) get_random because the set is copied into a list.

Optimal approach: array, index map, swap with last

items is a packed array of the members. where maps each member to its index in items. Insert appends to items and records the index. get_random picks a uniform index into items. Remove is the clever part: popping from the middle of an array is O(n), but popping from the end is O(1). So take the last element, write it into the slot of the value being removed, update its index in where, pop the end, and delete the removed value from where. Since a set has no order to preserve, moving one element costs nothing.

import random

class RandomizedSet:
    def __init__(self):
        self.items = []
        self.where = {}  # value -> index in items

    def insert(self, val):
        if val in self.where:
            return False
        self.where[val] = len(self.items)
        self.items.append(val)
        return True

    def remove(self, val):
        if val not in self.where:
            return False
        hole = self.where[val]
        last = self.items[-1]
        self.items[hole] = last
        self.where[last] = hole
        self.items.pop()
        del self.where[val]
        return True

    def get_random(self):
        return random.choice(self.items)
Python: two structures kept in step.
class RandomizedSet {
  constructor() {
    this.items = [];
    this.where = new Map();
  }

  insert(val) {
    if (this.where.has(val)) return false;
    this.where.set(val, this.items.length);
    this.items.push(val);
    return true;
  }

  remove(val) {
    if (!this.where.has(val)) return false;
    const hole = this.where.get(val);
    const last = this.items[this.items.length - 1];
    this.items[hole] = last;
    this.where.set(last, hole);
    this.items.pop();
    this.where.delete(val);
    return true;
  }

  getRandom() {
    return this.items[Math.floor(Math.random() * this.items.length)];
  }
}
JavaScript: a Map for positions and a plain array for values.

The order of updates in remove

Consider removing the value that is already last. Then last and val are the same, and hole is the final index. The code writes the value onto itself, sets its index to hole, pops the end, and finally deletes val from the map. Everything ends up correct. Now swap the last two steps in your head: delete val from the map first, then set where[last] = hole. Because last is val, that line puts val back into the map, pointing at an index that no longer exists. The next insert of val returns false, and get_random can crash. Write the map update for the moved element first and the delete last, and mention this case before the interviewer does.

Why get_random is uniform

The array always holds exactly the current members, each once, in positions 0 to n - 1 with no gaps, because removals fill holes from the end. A uniform random index therefore selects each member with probability 1 / n. Without the swap, a removed value would leave a gap, and you would either need to skip gaps (which biases picks toward values after long runs of gaps) or retry until you hit a live slot (which has no time bound).

Time and space

n members
Designinsertremoveget_randomSpace
Hash set onlyO(1) averageO(1) averageO(n)O(n)
Array onlyO(n), duplicate checkO(n)O(1)O(n)
Array plus index mapO(1) average, amortized appendO(1) averageO(1)O(n)
n members. Scroll sideways on a small screen.

Edge cases

  • Removing the only member leaves both structures empty, through the same code path as removing the last element.
  • Removing the element that sits last in the array, the case discussed above.
  • Inserting a value that was removed earlier works like a fresh insert.
  • Negative numbers and zero are ordinary keys in both languages.
  • get_random on an empty set is out of contract; ask whether to raise an error or return a sentinel if the interviewer wants it handled.

Mistakes to avoid

  • Deleting the removed value from the map before updating the moved value's index.
  • Removing from the middle of the array with a splice or del, which is O(n).
  • Forgetting to update the moved value's index at all, so later removes of it corrupt the array.
  • Converting the set to a list inside get_random and calling it O(1).
  • Choosing a random index with Math.round(Math.random() * length) instead of Math.floor, which gives the first element half the weight of the others and sometimes returns an index one past the end.

How to explain it out loud

Fictional example

Two structures, one invariant
Candidate
A set gives constant insert and remove but not random access, an array gives random access but slow lookup. I'll keep both: an array of members and a map from member to index.
Candidate
To remove, I copy the last member into the removed slot, update its index in the map, pop the end, then delete the removed value from the map. That order matters when the removed value is the last one.
Candidate
The array stays packed, so a uniform random index is a uniform member. All three are constant on average.

Random Pick With Weight changes uniform picks to weighted ones, and the data structure changes with it. Minimum Remove to Make Valid Parentheses is a change of pace, a string problem where you also mark items for removal and rebuild once. Design HashMap explains what the where map is doing underneath, and Two Sum is the simplest use of a value-to-index map.

Natively and this problem

In practice on Mac or Windows, Natively can capture the prompt from your screen and draft a solution, so you can compare your remove method line by line against another version. It also transcribes your spoken walkthrough, which shows whether you raised the remove-the-last-element case on your own. The AI interview assistant page explains how practice sessions work.

Questions people ask

How do you implement Insert Delete GetRandom in O(1)?

Keep an array of the members and a map from each member to its index. Insert appends and records the index. get_random picks a uniform index. Remove copies the last element into the removed slot, updates its index, pops the end and deletes the removed value from the map.

Why does the order of updates in remove matter?

If the removed value is already last, deleting it from the map before updating the moved value's index puts it back into the map, pointing at an index that no longer exists. Update the moved element first and delete the removed value last.

Why is get_random uniform?

Swap-with-last removal keeps the array packed, so it holds exactly the current members, each once, in positions 0 to n - 1. A uniform random index then selects each member with probability 1 / n.

How do you handle duplicates in Insert Delete GetRandom?

Map each value to a set of positions. get_random then picks each copy uniformly, so a value with three copies is three times as likely, and removal takes any one position from the set and does the same swap.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP