Practice/Udemy/Leetcode 380. Insert Delete GetRandom O(1)
CodingMust
Build a data structure that maintains a collection of unique integers and supports three operations, each completing in average O(1) time complexity:
true if the value was not already present (insertion succeeded), false if it already exists (insertion failed).true if the value was present (removal succeeded), false if it wasn't found (removal failed).The challenging aspect is achieving constant time for all operations while maintaining uniform random selection. Traditional data structures excel at some operations but not all three simultaneously.
insert operation should prevent duplicatesremove operation should only succeed if the element existsgetRandom operation must give each current element equal probabilitygetRandom will only be called when at least one element exists in the collectionExample 1: Basic functionality
` Operations: ["RandomSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] Parameters: [[], [1], [2], [2], [], [1], [2], []]
Output: [null, true, false, true, 2, true, true, 2]
Explanation:
Example 2: Duplicate handling
` Operations: ["RandomSet", "insert", "insert", "insert", "getRandom"] Parameters: [[], [5], [5], [10], []]
Output: [null, true, false, true, 5 or 10]
Explanation:
Example 3: Removal from empty collection
` Operations: ["RandomSet", "remove", "insert", "getRandom", "remove"] Parameters: [[], [100], [100], [], [100]]
Output: [null, false, true, 100, true]
Explanation: