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

MediumDesignArrayHash TableMathRandomized
Problem
#380
Reading time
6 min

The problem

Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present.

Example

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
Output
[null, true, false, true, 2, true, false, 2]
Explanation
RandomizedSet randomizedSet = new RandomizedSet();

Python solution

Python
class RandomizedSet:
    def __init__(self):
        self.d = {}
        self.q = []

    def insert(self, val: int) -> bool:
        if val in self.d:
            return False
        self.d[val] = len(self.q)
        self.q.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.d:
            return False
        i = self.d[val]
        self.d[self.q[-1]] = i
        self.q[i] = self.q[-1]
        self.q.pop()
        self.d.pop(val)
        return True

    def getRandom(self) -> int:
        return choice(self.q)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 380. Insert Delete GetRandom O(1) is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 380. Insert Delete GetRandom O(1)?
LeetCode 380. Insert Delete GetRandom O(1) is rated Medium on LeetCode.
What is the time complexity of LeetCode 380. Insert Delete GetRandom O(1)?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 380. Insert Delete GetRandom O(1)?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 380. Insert Delete GetRandom O(1) cover?
LeetCode 380. Insert Delete GetRandom O(1) is tagged Design, Array, Hash Table, Math and Randomized on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview