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))
Difficulty
and has an acceptance rate of about 55% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Design
- Hash Table
- Math
- Randomized
AI Disclaimer
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.
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 aKeyErrorthat would otherwise be raised byset.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
choicereceives 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
choicewill 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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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