Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

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

YASH PAL, 31 July 202422 January 2026

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

Leetcode Insert Delete GetRandom O(1) – Duplicates allowed 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

Insert Delete GetRandom O(1) – Duplicates allowed 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;
};

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes