Skip to content

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.

Medium#380
LeetCode Problem

Insert Delete GetRandom O(1)

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

Input
["RandomizedSet","insert","insert","insert","remove","getRandom","remove"]
[[],[4],[7],[4],[4],[],[4]]
Output
[null,true,true,false,true,7,false]
Explanation

Only 7 remains when sampled, so this particular random call has one possible result.

Constraints

-2^31 <= val <= 2^31 - 1
At most 2 * 10^5 total calls.
getRandom is called only when nonempty.

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.