Problem 380

Abstract / Summary

Design a data structure that supports adding removing and retrieving random elements all in constant time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0380.py

class RandomizedSet:
    def __init__(self):
        self.all = set() # assume hash set

    def insert(self, val: int) -> bool:
        if val not in self.all:
            self.all.add(val)
            return True
        else:
            return False

    def remove(self, val: int) -> bool:
        if val in self.all:
            self.all.remove(val)
            return True
        else:
            return False

    def getRandom(self) -> int:
        return choice(tuple(self.all))
20 lines | 511 bytes | submitted August 31, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Hash Table
  • Math
  • Randomized
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a RandomizedSet class that offers three core operations: insertion of a value, removal of a value, and retrieval of a random element. Internally the class relies on Python’s built-in hash set (set) to store the elements, which gives constant-time performance for membership checks, additions, and deletions. The random selection is performed by converting the set to an immutable sequence and using the standard library’s choice function.

Initialization

The constructor creates an empty hash set that will hold all integer values inserted into the structure.

def __init__(self):
    self.all = set()  # assume hash set

By using a hash set, the object is ready to support fast membership queries from the very beginning.

Insert Operation

The insert method first checks whether the supplied integer is already present. If the value is absent, it is added to the set and the method returns True. When the value already exists, the method skips the insertion and returns False. This conditional flow guarantees that duplicate entries are never stored.

def insert(self, val: int) -> bool:
    if val not in self.all:
        self.all.add(val)
        return True
    else:
        return False

Edge Cases Handled

  • Duplicate insertion - The presence test (val not in self.all) prevents a second copy of the same integer from being added, ensuring the set semantics are preserved.
  • Insertion of any integer - The method accepts any integer value, including zero and negative numbers, because the underlying set does not impose range restrictions.

Remove Operation

The remove method mirrors the logic of insert. It verifies that the target value exists before attempting deletion. If the value is found, it is removed from the set and the method returns True. If the value is missing, the method simply returns False without raising an exception.

def remove(self, val: int) -> bool:
    if val in self.all:
        self.all.remove(val)
        return True
    else:
        return False

Edge Cases Handled

  • Removal of a non-existent element - The membership test (val in self.all) prevents a KeyError that would otherwise be raised by set.remove.
  • Removal of the last element - When the set contains a single item, the method correctly empties the set while still returning True.

Get Random Operation

The getRandom method produces a random element from the current collection. It first materializes the set as a tuple, which provides an indexable sequence, and then selects an element using choice.

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

Edge Cases Handled

  • Random selection from a populated set - Converting the set to a tuple guarantees that choice receives a sequence with a defined length, allowing uniform random selection.
  • Implicit handling of a single-element set - When only one element is present, the tuple contains a single entry, and choice will always return that element, satisfying the contract of returning a random member.

Performance Optimizations

The design leverages the intrinsic properties of Python’s hash set to achieve fast operations. Membership checks (val in self.all) and modifications (self.all.add, self.all.remove) are executed in constant time on average, eliminating the need for linear scans.

For random access, the conversion to a tuple is performed only at the moment of selection, avoiding the overhead of maintaining a separate list that would need to stay synchronized with the set. This on-demand materialization keeps the memory footprint minimal when random access is infrequent, while still allowing the use of the highly optimized choice routine for uniform selection.

Overall, the class presents a concise and effective implementation of a set that supports constant-time insertions and deletions together with a straightforward mechanism for retrieving a random element.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a magical toy box that holds your favorite blocks. This code helps you manage what is inside that box.

When you start, the box is empty. This is the setup part where the box gets ready to hold your toys.

The insert part is like putting a new toy into the box. Before you put a new block in, you check if it is already there. If the block is new and not in the box, you place it inside. If the block is already sitting in the box, you do not need to add it again.

The remove part is for taking a toy out. You check to see if the block you want is inside the box. If you find the block, you take it out so you can play with it. If the block is not in the box, you just leave the box as it is.

The getRandom part is a fun game. You close your eyes, reach into the toy box, and pull out one block without looking. It is a surprise every time because you get to pick any block that is currently inside the box.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 1.89

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java TS Rust Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
Garvit244 Python
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TS
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
Garvit244 Python
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong TypeScript
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
54 links | 38 authors | 11 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality