KatInterview

O(1) Insert, Delete, and Fair Random Draw from a Live Set

Data Structure DesignModel answer
HardModel answerData Structure Designhash maparrayrandomization

Last updated

Design a data structure that supports adding, removing, and uniformly sampling integer values, all in average O(1) time with no duplicates.

O(1) Insert, Delete, and Fair Random Draw from a Live Set

A real-time pipeline tracks a changing collection of integer IDs. IDs are continuously added and expired, and at any moment the system needs to draw one ID at random — with every ID in the collection equally likely to be chosen.

Your job is to build a class LiveSet that keeps this collection and supports three operations, each running in average O(1) time:

  • insert(val) — adds val to the collection if it is not already there. Returns true on a successful insertion, false if val was already present (no change is made).
  • remove(val) — removes val from the collection if it is present. Returns true on a successful removal, false if val was not found (no change is made).
  • sample() — returns one element chosen uniformly at random from the current collection. Every element must have an equal chance of being returned. You may assume sample() is only called when the collection is non-empty.

The collection never holds duplicates. Inserting an existing value is always a no-op.

Example walkthrough

s = LiveSet()
s.insert(10)   -> true   (collection = {10})
s.remove(99)   -> false  (99 not present; collection = {10})
s.insert(20)   -> true   (collection = {10, 20})
s.sample()     -> 10 or 20, each with probability 1/2
s.remove(10)   -> true   (collection = {20})
s.insert(20)   -> false  (20 already present; collection = {20})
s.sample()     -> 20     (only element)

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 × 10^5 total calls across all three methods
  • sample() is only called when the collection has at least one element
  • All three operations must run in average O(1) — solutions that scan the collection linearly for any operation are not acceptable

Hints

Hint 1

Think about which standard structure lets you pick a random element in O(1): you need index-based access, which a hash set alone cannot give you. What if you also kept the elements in a list?

Hint 2

The hard part is deletion. Removing an element from the middle of a list normally requires shifting everything after it. Is there a way to fill the gap without moving more than one element? Order in the list doesn't matter here — only membership does.

Hint 3

When you swap the target element with the last element and pop the tail, you need to update the position map too. Be careful about what happens when the element you are removing is already the last one in the list — draw it out and make sure your update order handles that case without leaving stale entries.