Design a set supporting insert, delete and random selection in expected/amortized O(1) time.

Instruction: Design set semantics with hashable values, a dense array and an index map. Explain expected/amortized complexity, uniform random selection, duplicate insertion, missing deletion, empty retrieval and deletion of the last value.

Context: This question challenges the candidate to design a sophisticated data structure that achieves constant time complexity for three fundamental operations: insert, delete, and get_random. Candidates must describe the data structure's composition and the algorithms that facilitate these operations efficiently. The answer should include an explanation of how the data structure maintains its efficiency, especially when dealing with the randomness aspect in constant time.

Updated

Official answer

For a set of hashable values, combine a dense array with a map from value to array index. Removal replaces the deleted entry with the last one, then updates that value's index.

import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.positions = {}

    def insert(self, value):
        if value in self.positions:
            return False
        self.positions[value] = len(self.values)
        self.values.append(value)
        return True

    def delete(self, value):
        if value not in self.positions:
            return False
        index = self.positions[value]
        last = self.values[-1]
        self.values[index] = last
        self.positions[last] = index
        self.values.pop()
        del self.positions[value]
        return True

    def get_random(self):
        if not self.values:
            raise IndexError('empty set')
        return random.choice(self.values)

Each stored value occupies one index, so a uniform random index selects values uniformly. Deleting the last value also works. Duplicate insertion and missing deletion return False; random retrieval from an empty set raises an error. This is a set, not a multiset.

The usual O(1) claim is expected/amortized under constant-cost hashing/equality and the array/random-generator model; resizing or adversarial collisions can cost more. Space is O(n). Values must keep stable hash/equality behavior while stored. This example is not thread-safe, does not preserve insertion order after deletion, and its random generator is unsuitable for security-sensitive selection.

Related Questions