Skip to content
AI360Xpert
Back to System-Design-Adjacent / OOP Coding
Medium

Insert Delete GetRandom O(1)

Implement the `RandomizedSet` class: - `RandomizedSet()` Initializes the `RandomizedSet` object. - `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. - `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. - `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.

Examples

Input:["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []]
Output:[null, true, false, true, 2, true, false, 2]
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

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

Optimal Solution

Approach

To achieve O(1) average time complexity for `insert`, `remove`, and `getRandom`, we need to use a combination of a hash map and a dynamic array (or list). 1. **Dynamic Array**: We store the elements in an array. This allows us to access a random element in O(1) time by picking a random index between `0` and `length - 1`. 2. **Hash Map**: We use a hash map to store the mapping from a value to its index in the array. This allows us to check if an element exists and find its location in O(1) time. **Insert Operation**: - Check if the value exists in the hash map. If it does, return `false`. - If not, append the value to the end of the array. - Add the value and its index (which is `array.length - 1`) to the hash map. - Return `true`. **Remove Operation**: - Check if the value exists in the hash map. If not, return `false`. - To remove an element in O(1) time from an array without shifting elements, we can swap the element to be removed with the **last element** in the array. - Get the index of the element to remove from the hash map. - Get the value of the last element in the array. - Swap the elements: set the value at the removed element's index to the last element's value. - Update the hash map: update the index of the last element's value to the removed element's index. - Remove the last element from the array (which is now O(1)). - Remove the deleted element's entry from the hash map. - Return `true`. **GetRandom Operation**: - Generate a random integer between `0` and the current size of the array minus 1. - Return the element at that random index in the array.

Complexity Analysis

Time Complexity
O(1)
Space Complexity
O(N)
Solution.java
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Random;
class RandomizedSet {    private Map<Integer, Integer> dict;    private List<Integer> list;    private Random rand;
    public RandomizedSet() {        dict = new HashMap<>();        list = new ArrayList<>();        rand = new Random();    }        public boolean insert(int val) {        if (dict.containsKey(val)) {            return false;        }        dict.put(val, list.size());        list.add(val);        return true;    }        public boolean remove(int val) {        if (!dict.containsKey(val)) {            return false;        }                int lastElement = list.get(list.size() - 1);        int idxToRemove = dict.get(val);                list.set(idxToRemove, lastElement);        dict.put(lastElement, idxToRemove);                list.remove(list.size() - 1);        dict.remove(val);        return true;    }        public int getRandom() {        return list.get(rand.nextInt(list.size()));    }}