KatInterview

Duplicate-Aware Collection with O(1) Random Sampling

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-maparrayrandomness

Last updated

Design a multiset supporting insert, remove, and uniform random sampling over all occurrences, each in expected O(1) time.

Duplicate-Aware Collection with O(1) Random Sampling

You need to build a collection that stores integers, allows duplicates, and supports three operations, each running in expected O(1) time:

  • insert(val: int) -> bool: Store one copy of val. Return True if val had zero copies before this call, False otherwise.
  • remove(val: int) -> bool: Erase one copy of val if any exist. Return True if a copy was found and removed, False if val was absent.
  • getRandom() -> int: Return one element chosen uniformly at random across every stored copy. A value with three copies must be three times as likely to be returned as a value with one copy. You may assume this is never called on an empty collection.

What to implement

class RandomizedCollection:
    def __init__(self): ...
    def insert(self, val: int) -> bool: ...
    def remove(self, val: int) -> bool: ...
    def getRandom(self) -> int: ...

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls across all three methods combined.
  • getRandom is only called when the collection is non-empty.

What is expected in your answer

Explain your choice of underlying data structures and why no single structure is sufficient. Walk through the deletion logic in detail, including what happens when the element you are removing happens to sit at the end of your backing array, and what happens when the value you are relocating during deletion is the same value you are removing. Discuss complexity and any invariants your design must maintain.

Hints

Hint 1

getRandom needs O(1) uniform sampling — think about which data structure lets you pick a random slot directly. A hash map alone cannot do this, but a plain array can.

Hint 2

To delete from an arbitrary position in an array in O(1), overwrite that slot with the last element and shrink the array by one. You just need a way to find the slot for any given value in O(1) — that is where a map from value to index comes in. With duplicates, one value can occupy multiple slots, so the map needs to store a collection of indices.

Hint 3

The trickiest deletion case is when the value you are removing is the same as the value at the end of the array (which you are swapping in to fill the gap). Make sure your index bookkeeping handles the situation where both pointers refer to the same index set before you start modifying it.