KatInterview

Multiset with O(1) Insert, Delete, and Uniform Random Sampling

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structureshash-tablesrandomization

Last updated

Build a collection supporting duplicates with constant-time insertion, deletion, and uniform random selection from all stored occurrences.

You need to implement a collection that stores strings and allows the same string to appear multiple times. The collection must support three operations, each running in average O(1) time:

class StringMultiset:
    def add(self, s: str) -> bool: ...
    def delete(self, s: str) -> bool: ...
    def pick_random(self) -> str: ...

Operation specifications:

  • add(s) stores one copy of string s, even if s already exists in the collection. Return True if this is the first occurrence of s being added, False if s was already present.

  • delete(s) removes exactly one occurrence of s if any exist. Return True if an occurrence was successfully removed, False if s was not found.

  • pick_random() returns one element selected uniformly at random from all stored occurrences. If a string appears k times among n total stored elements, it should be returned with probability k/n.

Assumptions and constraints:

  • Strings may have arbitrary length
  • Hash operations and string equality checks can be treated as O(1) for complexity analysis
  • The collection may be empty when pick_random() is called (specify your behavior)
  • Multiple occurrences of the same string must be tracked independently

Example:

ms = StringMultiset()
ms.add("apple")     # returns True (first occurrence)
ms.add("apple")     # returns False (already present)
ms.add("banana")    # returns True
ms.pick_random()    # returns "apple" with probability 2/3, "banana" with probability 1/3
ms.delete("apple")  # returns True (one occurrence removed)
ms.pick_random()    # returns "apple" with probability 1/2, "banana" with probability 1/2
ms.delete("cherry") # returns False (not present)

Hints

Hint 1

Random access suggests storing elements in a contiguous structure where you can index directly

Hint 2

Deletion from the middle of an array is expensive, but swapping with the last element is cheap

Hint 3

You need a way to quickly locate where each string's occurrences are stored