
Problem
Solution
Submissions
RandomizedSet
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a Python class that implements a data structure RandomizedSet
supporting insert, remove, and getRandom operations in average O(1) time complexity.
Example 1
- Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []]
- Output: [null, true, false, true, 2, true, false, 2]
- Explanation:
- Step 1: Initialize RandomizedSet.
- Step 2: insert(1) → true, 1 added.
- Step 3: remove(2) → false, 2 not present.
- Step 4: insert(2) → true, 2 added.
- Step 5: getRandom() → returns either 1 or 2.
- Step 6: remove(1) → true, 1 removed.
- Step 7: insert(2) → false, 2 already present.
- Step 8: getRandom() → returns 2.
Example 2
- Input: ["RandomizedSet", "insert", "insert", "remove", "insert", "remove", "getRandom"] [[], [1], [2], [1], [2], [2], []]
- Output: [null, true, true, true, false, true, 1]
- Explanation:
- Step 1: Initialize RandomizedSet.
- Step 2: insert(1) → true.
- Step 3: insert(2) → true.
- Step 4: remove(1) → true.
- Step 5: insert(2) → false.
- Step 6: remove(2) → true.
- Step 7: getRandom() → returns 1 (set is now empty so behavior may vary).
Constraints
- -231 ≤ val ≤ 231 - 1
- At most 2 × 105 calls will be made to insert, remove, and getRandom
- There will be at least one element in the data structure when getRandom is called
- Time Complexity: O(1) average for all operations
- Space Complexity: O(n) where n is the number of elements in the set
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a combination of a hashmap and an array
- The hashmap provides O(1) lookup for checking existence and retrieving positions
- The array allows O(1) random access for the getRandom operation
- For efficient removal, swap the element to be removed with the last element in the array
- Update the hashmap accordingly after each operation