← Questions

Insert, delete and get random in O(1)

0
UberMetaSpaceXAICodingLast asked May 2026

A coding interview question asked in Uber's technical phone screen and at Meta and SpaceXAI, last asked May 2026. It tests hash maps, arrays and randomization.

Design a set of integers that supports insert, remove and pick-a-random-element, each in average O(1) time. A random pick returns every element currently in the set with equal probability.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • insert(val: int) -> bool — adds val; returns False if it was already present.
  • remove(val: int) -> bool — removes val; returns False if it was absent.
  • get_random() -> int — a uniformly random element. It is only called when the set is non-empty.

Example

s = RandomizedSet()
s.insert(1)       ->  True
s.remove(2)       ->  False
s.insert(2)       ->  True
s.get_random()    ->  1 or 2, each with probability 1/2
s.remove(1)       ->  True
s.insert(2)       ->  False
s.get_random()    ->  2

Constraints

  • Up to 2 × 10^5 calls; values fit in 32 bits.

Clarifying questions

  • Are duplicates allowed? (The base problem says no.)
  • What should get_random do on an empty set?
  • Is average O(1) enough, or is worst case required?
  • Will it be used from several threads?

What a strong answer covers

  • An array holding the elements plus a hash map from value to its index in the array.
  • Remove in O(1): move the last element into the removed slot, update its index in the map, then pop the last slot.
  • get_random picks a random array index, which is uniform because the array has no holes.
  • Why a hash set alone cannot pick uniformly in O(1).
  • Tests: remove the last element, remove the only element, insert after remove.

Follow-ups

  • Allow duplicates: each copy should be picked with equal probability (a map from value to a set of indices).
  • Make it safe for concurrent callers.
  • Add get_random_weighted(), where each value has a weight.

Where it's asked

  • Uber · Technical phone screen · Last asked May 202660 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
  • Meta · Technical phone screen · Last asked Mar 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
  • SpaceXAI · Technical phone screen · Last asked Sep 202545 min · Live applied coding on a shared platform such as CoderPad · No AI

What it tests

hash maps · arrays · randomization

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding