Practice Insert Delete GetRandom O(1)
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
RandomizedSet starts empty. insert(val) adds an absent value and reports whether it was new; remove(val) deletes a present value and reports success. getRandom() uniformly samples the current distinct values. All three operations require average O(1) time. Practice approach: Combine a dense value array with a value-to-index map. Delete by moving the final array entry into the removed slot and updating its index. Sample an array index uniformly. Updating the moved entry is essential when removing a nonfinal value.
Source: Insert Delete GetRandom O(1) on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
["RandomizedSet","insert","insert","insert","remove","getRandom","remove"] [[],[4],[7],[4],[4],[],[4]]
[null,true,true,false,true,7,false]
Only 7 remains when sampled, so this particular random call has one possible result.
Constraints
Related LeetCode Problems
Practice more problems similar to Insert Delete GetRandom O(1).
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.