# 0380-insert-delete-getrandom-o1 Try it on leetcode ## Description

Implement the RandomizedSet class:

You must implement the functions of the class such that each function works 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
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

 

Constraints:

## Solution(Python) ```Python # Data structure # for O(1) access -> hashmap # for random access -> array # use combination of array and hashmap # hahsmap -> key -> index at array # array -> list of keys import random class RandomizedSet: def __init__(self): self.hash = {} self.array = [] def insert(self, val: int) -> bool: if val in self.hash: return False self.array.append(val) self.hash[val] = len(self.array) - 1 return True def remove(self, val: int) -> bool: if val not in self.hash: return False idx = self.hash[val] last_idx = len(self.array) - 1 last_index_element = self.array[last_idx] self.array[idx] = self.array[last_idx] self.hash[last_index_element] = idx del self.hash[val] self.array.pop() return True def getRandom(self) -> int: return random.choice(self.array) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom() ```