Welcome to Subscribe On Youtube

380. Insert Delete GetRandom O(1)

Description

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.

 

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:

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

Solutions

Solution 1: Hash Table + Dynamic List

We define a dynamic list $q$ to store the elements in the set, and a hash table $d$ to store the index of each element in $q$.

When inserting an element, if the element already exists in the hash table $d$, return false directly; otherwise, we insert the element into the end of the dynamic list $q$, and insert the element and its index in $q$ into the hash table $d$ at the same time, and finally return true.

When deleting an element, if the element does not exist in the hash table $d$, return false directly; otherwise, we obtain the index of the element in the list $q$ from the hash table, then swap the last element $q[-1]$ in the list $q$ with $q[i]$, and then update the index of $q[-1]$ in the hash table to $i$. Then delete the last element in $q$, and remove the element from the hash table at the same time, and finally return true.

When getting a random element, we can randomly select an element from the dynamic list $q$ and return it.

Time complexity $O(1)$, space complexity $O(n)$, where $n$ is the number of elements in the set.

  • class RandomizedSet {
        private Map<Integer, Integer> d = new HashMap<>();
        private List<Integer> q = new ArrayList<>();
        private Random rnd = new Random();
    
        public RandomizedSet() {
        }
    
        public boolean insert(int val) {
            if (d.containsKey(val)) {
                return false;
            }
            d.put(val, q.size());
            q.add(val);
            return true;
        }
    
        public boolean remove(int val) {
            if (!d.containsKey(val)) {
                return false;
            }
            int i = d.get(val);
            d.put(q.get(q.size() - 1), i);
            q.set(i, q.get(q.size() - 1));
            q.remove(q.size() - 1);
            d.remove(val);
            return true;
        }
    
        public int getRandom() {
            return q.get(rnd.nextInt(q.size()));
        }
    }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet obj = new RandomizedSet();
     * boolean param_1 = obj.insert(val);
     * boolean param_2 = obj.remove(val);
     * int param_3 = obj.getRandom();
     */
    
    
    /////////
    
    public class Insert_Delete_GetRandom_O_1 {
    
        public static void main(String[] args) {
    
            Insert_Delete_GetRandom_O_1 out = new Insert_Delete_GetRandom_O_1();
    
            // Init an empty set.
            RandomizedSet randomSet = out.new RandomizedSet();
    
            System.out.println(randomSet.remove(0));
            System.out.println(randomSet.remove(0));
            System.out.println(randomSet.insert(0));
            System.out.println(randomSet.insert(0));
            System.out.println(randomSet.insert(0));
    
            System.out.println(randomSet.getRandom());
    
            System.out.println(randomSet.remove(0));
            System.out.println(randomSet.insert(0));
        }
    
        class RandomizedSet {
    
            List<Integer> list;
            Map<Integer, Integer> map; // val => its index in list
            Random random;
    
            /** Initialize your data structure here. */
            public RandomizedSet() {
                list = new ArrayList<>();
                map = new HashMap<>();
                random = new Random();
            }
    
            /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
            public boolean insert(int val) {
                if (map.containsKey(val)) {
                    return false;
                }
    
                int pos = list.size();
    
                list.add(val);
                map.put(val, pos);
    
                return true;
            }
    
            /** Removes a value from the set. Returns true if the set contained the specified element. */
            public boolean remove(int val) {
                if (!map.containsKey(val)) {
                    return false;
                }
    
                // swap val to end of list, then remove it
                int pos = map.get(val);
                int lastVal = list.get(list.size() - 1);
    
                list.set(pos, lastVal);
                list.remove(list.size() - 1);
    
                map.put(lastVal, pos); // @note: missed this line
                map.remove(val);
    
                return true;
            }
    
            /** Get a random element from the set. */
            public int getRandom() {
                int randIndex = random.nextInt(list.size());
                return list.get(randIndex);
            }
        }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet obj = new RandomizedSet();
     * boolean param_1 = obj.insert(val);
     * boolean param_2 = obj.remove(val);
     * int param_3 = obj.getRandom();
     */
    }
    
    
  • class RandomizedSet {
    public:
        RandomizedSet() {
        }
    
        bool insert(int val) {
            if (d.count(val)) {
                return false;
            }
            d[val] = q.size();
            q.push_back(val);
            return true;
        }
    
        bool remove(int val) {
            if (!d.count(val)) {
                return false;
            }
            int i = d[val];
            d[q.back()] = i;
            q[i] = q.back();
            q.pop_back();
            d.erase(val);
            return true;
        }
    
        int getRandom() {
            return q[rand() % q.size()];
        }
    
    private:
        unordered_map<int, int> d;
        vector<int> q;
    };
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet* obj = new RandomizedSet();
     * bool param_1 = obj->insert(val);
     * bool param_2 = obj->remove(val);
     * int param_3 = obj->getRandom();
     */
    
  • '''
    my_dict.pop('b') # vs del d[k]
    
        my_dict = {'a': 1, 'b': 2, 'c': 3}
        val = my_dict.pop('b')
        print(my_dict)  # {'a': 1, 'c': 3}
        print(val)  # 2
    
        >>> item = my_dict.pop()
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: pop expected at least 1 argument, got 0
    
        >>> my_dict = {'a': 1, 'b': 2, 'c': 3}
        >>> del my_dict['b']
        >>> my_dict
        {'a': 1, 'c': 3}
    '''
    
    from collections import defaultdict
    from random import choice
    
    class RandomizedSet(object):
      def __init__(self):
        """
        Initialize your data structure here.
        """
    
        # value (map) -> its index -> value (list)
        self.d = {}
        self.a = [] # introduce it purely for random
    
      def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.d:
          return False
        self.a.append(val)
        self.d[val] = len(self.a) - 1
        return True
    
      def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.d:
          return False
        index = self.d[val]
    
        # process last index/val
        self.a[index] = self.a[-1]
        self.d[self.a[-1]] = index
    
        # process to be deleted index/val
        self.a.pop() # delete in list
        del self.d[val] # delete in dict
        # or, self.d.pop(val)
        return True
    
      def getRandom(self):
        """
        Get a random element from the set.
        :rtype: int
        """
        return self.a[random.randrange(0, len(self.a))]
        # return random.choice(self.a)
    
    ############
    
    # 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()
    
    '''
    >>> import random
    >>> random.choice([1,2,3,4,5])
    3
    >>> random.choice([1,2,3,4,5])
    4
    >>> random.choice([1,2,3,4,5])
    4
    '''
    class RandomizedSet:
        def __init__(self):
            self.m = {}
            self.l = []
    
        def insert(self, val: int) -> bool:
            if val in self.m:
                return False
            self.m[val] = len(self.l)
            self.l.append(val)
            return True
    
        def remove(self, val: int) -> bool:
            if val not in self.m:
                return False
            idx = self.m[val]
            self.l[idx] = self.l[-1]
            self.m[self.l[-1]] = idx
            self.l.pop()
            self.m.pop(val)
            return True
    
        def getRandom(self) -> int:
            return random.choice(self.l)
    
    
    # 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()
    
    
  • type RandomizedSet struct {
    	d map[int]int
    	q []int
    }
    
    func Constructor() RandomizedSet {
    	return RandomizedSet{map[int]int{}, []int{} }
    }
    
    func (this *RandomizedSet) Insert(val int) bool {
    	if _, ok := this.d[val]; ok {
    		return false
    	}
    	this.d[val] = len(this.q)
    	this.q = append(this.q, val)
    	return true
    }
    
    func (this *RandomizedSet) Remove(val int) bool {
    	if _, ok := this.d[val]; !ok {
    		return false
    	}
    	i := this.d[val]
    	this.d[this.q[len(this.q)-1]] = i
    	this.q[i] = this.q[len(this.q)-1]
    	this.q = this.q[:len(this.q)-1]
    	delete(this.d, val)
    	return true
    }
    
    func (this *RandomizedSet) GetRandom() int {
    	return this.q[rand.Intn(len(this.q))]
    }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * obj := Constructor();
     * param_1 := obj.Insert(val);
     * param_2 := obj.Remove(val);
     * param_3 := obj.GetRandom();
     */
    
  • class RandomizedSet {
        private d: Map<number, number> = new Map();
        private q: number[] = [];
    
        constructor() {}
    
        insert(val: number): boolean {
            if (this.d.has(val)) {
                return false;
            }
            this.d.set(val, this.q.length);
            this.q.push(val);
            return true;
        }
    
        remove(val: number): boolean {
            if (!this.d.has(val)) {
                return false;
            }
            const i = this.d.get(val)!;
            this.d.set(this.q[this.q.length - 1], i);
            this.q[i] = this.q[this.q.length - 1];
            this.q.pop();
            this.d.delete(val);
            return true;
        }
    
        getRandom(): number {
            return this.q[Math.floor(Math.random() * this.q.length)];
        }
    }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * var obj = new RandomizedSet()
     * var param_1 = obj.insert(val)
     * var param_2 = obj.remove(val)
     * var param_3 = obj.getRandom()
     */
    
    
  • public class RandomizedSet {
        private Dictionary<int, int> d = new Dictionary<int, int>();
        private List<int> q = new List<int>();
    
        public RandomizedSet() {
    
        }
        
        public bool Insert(int val) {
            if (d.ContainsKey(val)) {
                return false;
            }
            d.Add(val, q.Count);
            q.Add(val);
            return true;
        }
        
        public bool Remove(int val) {
            if (!d.ContainsKey(val)) {
                return false;
            }
            int i = d[val];
            d[q[q.Count - 1]] = i;
            q[i] = q[q.Count - 1];
            q.RemoveAt(q.Count - 1);
            d.Remove(val);
            return true;
        }
        
        public int GetRandom() {
            return q[new Random().Next(0, q.Count)];
        }
    }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet obj = new RandomizedSet();
     * bool param_1 = obj.Insert(val);
     * bool param_2 = obj.Remove(val);
     * int param_3 = obj.GetRandom();
     */
    
  • use std::collections::HashSet;
    use rand::Rng;
    
    struct RandomizedSet {
        list: HashSet<i32>,
    }
    
    /**
     * `&self` means the method takes an immutable reference.
     * If you need a mutable reference, change it to `&mut self` instead.
     */
    impl RandomizedSet {
        fn new() -> Self {
            Self {
                list: HashSet::new(),
            }
        }
    
        fn insert(&mut self, val: i32) -> bool {
            self.list.insert(val)
        }
    
        fn remove(&mut self, val: i32) -> bool {
            self.list.remove(&val)
        }
    
        fn get_random(&self) -> i32 {
            let i = rand::thread_rng().gen_range(0, self.list.len());
            *self.list.iter().collect::<Vec<&i32>>()[i]
        }
    }/**
     * Your RandomizedSet object will be instantiated and called as such:
     * let obj = RandomizedSet::new();
     * let ret_1: bool = obj.insert(val);
     * let ret_2: bool = obj.remove(val);
     * let ret_3: i32 = obj.get_random();
     */
    
    

All Problems

All Solutions