LeetCode 380: Insert Delete GetRandom O(1) — Python Solution

LeetCode 380: Insert Delete GetRandom O(1) is a Medium array / string problem. This Python walkthrough develops an array plus index map solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patternarray plus index map
ComplexityO(1) average time per operation and O(n) space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, store values densely in an array and map each value to its index. Removal swaps the target with the last value before popping. The invariant worth writing beside the code is: The map always records the current array index of every stored value.

Step-by-step algorithm

  1. Identify the input state consumed by insert(val) and initialize the data required by the array plus index map pattern.
  2. Store values densely in an array and map each value to its index. Removal swaps the target with the last value before popping.
  3. After each update, verify the page’s central invariant: The map always records the current array index of every stored value.
  4. Finish only after the boundary behavior is covered: Removing the final element and reinserting a deleted value must update both structures.

Python solution

import random

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

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

    def remove(self, val):
        if val not in self.index:
            return False
        i = self.index.pop(val)
        last = self.values.pop()
        if i < len(self.values):
            self.values[i] = last
            self.index[last] = i
        return True

    def getRandom(self):
        return random.choice(self.values)

Reading the implementation

The main entry point is insert(val). The named working state includes i, last; those variables make the array plus index map state visible instead of hiding it in incidental control flow.

The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, store values densely in an array and map each value to its index. Removal swaps the target with the last value before popping.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Store values densely in an array and map each value to its index. Removal swaps the target with the last value before popping. Each update records the current item without invalidating earlier decisions; consequently, the map always records the current array index of every stored value.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(1) average time per operation and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

rs=RandomizedSet(); assert rs.insert(1) and not rs.remove(2) and rs.insert(2) and rs.getRandom() in {1,2} and rs.remove(1)

Common mistakes and edge cases

  • Problem-specific boundary: Removing the final element and reinserting a deleted value must update both structures.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that the map always records the current array index of every stored value.

Interview review checklist

  • Explain why array plus index map matches the structure of this input.
  • State the invariant in one sentence before tracing code: The map always records the current array index of every stored value.
  • Derive O(1) average time per operation and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: Removing the final element and reinserting a deleted value must update both structures.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 274. H-Index · Next: 238. Product of Array Except Self