Insert Delete GetRandom O(1) - Duplicates allowed in C++

Suppose, we want to make a data structure, that supports some operations, these operations must be preformed in O(1) amount of time. So let these operations are like −

  • insert(x): insert x into the collection
  • remove(x): delete x from the collection
  • getRandom(): This will find random element form that collection.

To solve this, we will follow these steps −

  • Make an array nums
  • make one map m
  • Define a function insert(), this will take val,
  • ret := when val is not in m
  • insert size of nums at the end of m[val]
  • insert { val, size of m[val] – 1} pair at the end of nums
  • return ret
  • Define a function remove(), this will take val,
  • ret := when val is not in m
  • if ret is non-zero, then −
    • last = last element of nums
    • m[key of last][value of last] := last element of m[val]
    • nums[last element of [m[val]] := last
    • delete last element from m[val]
    • if m[val] is empty, then −
      • delete val from m
    • delete last element from nums
  • return ret
  • Define a function getRandom()
  • return one random element from the collection

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class RandomizedCollection {
   vector <pair <int, int>> nums;
   unordered_map <int, vector<int>> m;
   RandomizedCollection() {
   bool insert(int val) {
      bool ret = m.find(val) == m.end();
      nums.push_back({val, m[val].size() - 1});
      return ret;
   bool remove(int val) {
      bool ret = m.find(val) != m.end();
         pair <int, int> last = nums.back();
         m[last.first][last.second] = m[val].back();
         nums[m[val].back()] = last;
      return ret;
   int getRandom() {
      return nums[rand() % nums.size()].first;
   RandomizedCollection ob;
   cout << (ob.getRandom()) << endl;
   cout << (ob.getRandom()) << endl;


Insert 10, 35, 20, 40, then get one random number, say 40, then remove 20, again get random element, that is say 35.



Updated on: 01-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started