KatInterview

Random Draw from a Mutable Membership Set in O(1)

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-maparrayrandomized

Last updated

Build a container that registers and removes integer keys and returns a uniformly random current key, all in average constant time.

You are maintaining the set of workers who are currently free to take jobs. Workers come and go constantly, and whenever a job arrives you must hand it to one of the free workers, picked uniformly at random.

Implement a class CandidatePool (in your language, a struct/class with the same three methods):

  • init() — creates an empty pool.
  • add(worker_id: int) -> bool — inserts worker_id if it is not already in the pool. Returns True when the insert happened, False when the id was already present (nothing changes in that case).
  • remove(worker_id: int) -> bool — deletes worker_id if present. Returns True when it was removed, False when it was absent (nothing changes).
  • pick() -> int — returns a currently registered id, where every registered id has the same probability of being chosen. Returns -1 if the pool holds nothing.

Every one of the three operations must run in average O(1) time. You may call remove and add in any interleaving, register an id again after it was removed, and use any 32-bit signed integer as an id (negative ids are fine).

Example:

p = CandidatePool()
p.add(7)        # True
p.remove(9)     # False
p.add(9)        # True
p.pick()        # 7 or 9, 50% each
p.remove(7)     # True
p.add(9)        # False
p.pick()        # 9
p.remove(9)     # True
p.pick()        # -1

Hints

Hint 1

A hash set answers membership in O(1) but can't be indexed, so it can't give you a uniform random element cheaply. A plain array indexes in O(1) but deletes from the middle in O(n). Combine them.

Hint 2

Keep the array gap-free: never leave holes. When you delete, fill the hole with the array's last element and shrink from the tail.

Hint 3

Store a map from id to its position in the array so deletion knows where the hole is. Remember to fix the moved element's recorded position, and mind the case where the removed element is itself the last one.