In this Leetcode Insert Delete GetRandom O(1) - Duplicates allowed problem solution you need to Implement the RandomizedCollection class:

RandomizedCollection() Initializes the RandomizedCollection object.

  1. bool insert(int val) Inserts an item val into the multiset if not present. Returns true if the item was not present, false otherwise.
  2. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item was present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
  3. int getRandom() Returns a random element from the current multiset of elements (it's guaranteed that at least one element exists when this method is called). The probability of each element being returned is linearly related to the number of same values the multiset contains.

You must implement the functions of the class such that each function works in average O(1) time complexity.

Leetcode Insert Delete GetRandom O(1) - Duplicates allowed problem solution


Problem solution in Python.

from collections import defaultdict
import random

class RandomizedCollection:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.deleted = []
        self.hm = defaultdict(list)
        self.arr = []
        
    
    def _rebuild(self):
        arr = []
        hm = defaultdict(list)

        for v in self.arr:
            if v != None:
                hm[v].append(len(arr))
                arr.append(v)
                
        self.arr = arr
        self.hm = hm
        self.deleted = []
        
    def insert(self, val: int) -> bool:
        """
        Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
        """
        if len(self.deleted):
            ind = self.deleted.pop()
            self.arr[ind] = val
        else:
            ind = len(self.arr)
            self.arr.append(val)
        self.hm[val].append(ind)
        
        return 1 == len(self.hm[val])

    def remove(self, val: int) -> bool:
        """
        Removes a value from the collection. Returns true if the collection contained the specified element.
        """
        l = self.hm[val]
        if not len(l):
            return False
        ind = l.pop()
        self.arr[ind] = None
        self.deleted.append(ind)
        
        if len(self.arr) < 2 * len(self.deleted):
            self._rebuild()
    
        return True
    

    def getRandom(self) -> int:
        """
        Get a random element from the collection.
        """
        val = None
        while val is None:
            val = random.choice(self.arr)
        return val



Problem solution in Java.

class RandomizedCollection {

 List<Integer> list;
public RandomizedCollection() {
    
    list = new ArrayList<>();
    
}

public boolean insert(int val) {
    
       
       if(list.contains(val)){
           list.add(val);
            return false;
       }
       else{
            list.add(val);
            return true;
       }
        
}

public boolean remove(int val) {
    
       if(list.contains(val)){
        list.remove(Integer.valueOf(val));
        return true;
    }else
        return false;
}

public int getRandom() {
     return list.get((int) (Math.random()*list.size()));
}


Problem solution in C++.

class RandomizedCollection {
public:
    RandomizedCollection() {
        srand(time(NULL));
    }

    bool insert(int val) {
        bool flag=false;
        v.push_back(val);
        if(!mapNumPos.count(val)) {
            mapNumPos[val]=set<int>();
            flag=true;
        }
        mapNumPos[val].insert(v.size()-1);
        return flag;
        
    }
    
    bool remove(int val) {
        bool flag=false;
        if(mapNumPos.count(val)) {
            flag=true;
            set<int> pos=mapNumPos[val];
            int delPos = *pos.begin();
            int lastPos=v.size()-1;
            int lastNum=v[lastPos];

            swap(v[delPos], v[lastPos]);
            v.pop_back();
            mapNumPos[val].erase(delPos);
            if(mapNumPos[val].size() == 0) {
                mapNumPos.erase(val);
            }

            if(mapNumPos.count(lastNum)) {
                mapNumPos[lastNum].erase(lastPos);
                mapNumPos[lastNum].insert(delPos);
            }
           
        }
        return flag;
    }

    int getRandom() {
        int n=v.size();
        int pos = rand()%n;
        int val=v[pos];
        return val;
        
    }
private:
    vector<int> v;
    unordered_map<int, set<int>> mapNumPos;
};