Insert Delete GetRandom O(1)

Medium · Design · Array · Hash Table · Math · Design · Randomized

Problem

Build a set of integers with three operations, each running in average O(1) time:

The hard part is getting all three at once. A hash set adds and removes in O(1) but cannot pick a random member without walking through it. A list picks a random position in O(1) but removes from the middle in O(n).

Tests replay a call sequence: the first entry names the class, each later entry is a method with its arguments, and calls returning nothing report None. Because getRandom is random, the expected list shows one possible run. Any member of the set at that moment is accepted. The long tests also count the draws: when getRandom is called thousands of times on a set that does not change, each member's count must be within 7 standard deviations of its fair share. A fair getRandom falls outside that band with probability below one in a billion. An implementation that favours one member, or never returns another, fails.

Examples

Input: insert(1), remove(2), insert(2), getRandom(), remove(1), insert(2), getRandom()
Output: True, False, True, 1 or 2, True, False, then 2

remove(2) fails because 2 is not in the set yet. The first getRandom may return either member, each half the time. After 1 is removed only 2 is left, and inserting 2 again changes nothing.

Input: insert(5), insert(5), getRandom(), remove(5), insert(5)
Output: True, False, 5, True, then True

A value is stored once, so the second insert(5) is refused. After removing it, it can be inserted again.

Constraints

Approaches

Follow-up

What if the same value may be inserted several times and every copy counts (LeetCode 381)? Keep a set of indices per value instead of a single index.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…