KatInterview

Count-Weighted Random Sampling with Dynamic Insertions and Removals

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designhash-maparraysrandomization

Last updated

Design a multiset supporting constant-time insert, remove, and random selection where each element's pick probability is proportional to its frequency.

Build a data structure that maintains a multiset of integers (a collection allowing duplicates) and supports three operations, each running in average O(1) time:

  • insert(val) → bool: Add one copy of val to the multiset. Return True if this is the first occurrence of val being added (the value was not present before), otherwise return False.

  • remove(val) → bool: If at least one copy of val exists in the multiset, remove exactly one copy and return True. If val is not present, return False.

  • get_random() → int: Return a uniformly random element from the underlying list of all stored copies. Each stored copy has equal probability of being selected, so a value appearing k times is k times as likely to be picked as a value appearing once.

For example, if the multiset contains [5, 5, 5, 9], calling get_random() should return 5 with probability 3/4 and 9 with probability 1/4.

Implement the structure by writing a driver function that processes a sequence of operations and returns the list of results.

Constraints

  • -2³¹ ≤ val ≤ 2³¹ - 1
  • At most 2 × 10⁵ total operations will be performed
  • get_random() is never called on an empty multiset

Examples

Example 1

Input: run_multiset_operations(['insert', 'insert', 'insert', 'get_random', 'remove', 'get_random'], [[1], [1], [2], [], [1], []], 7)

Output: [True, False, True, 1, True, 2]

Example 2

Input: run_multiset_operations(['insert', 'insert', 'remove', 'insert', 'get_random', 'remove', 'remove'], [[-4], [0], [-4], [-4], [], [0], [-4], []], 19)

Output: [True, True, True, True, 0, True, True]

Hints

Hint 1

Store all element copies in a list so you can pick a random index in O(1). Use a hash map to track which indices hold each value.

Hint 2

When removing an element, swap it with the last element in the list to avoid shifting. Remember to update the index mapping for the element you moved.

Hint 3

Watch the edge case where the element being removed is already at the last position, or when the swapped element has the same value as the one being removed.