- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Example
#include <bits/stdc++.h> using namespace std; class RandomizedCollection { public: vector <pair <int, int>> nums; unordered_map <int, vector<int>> m; RandomizedCollection() { } bool insert(int val) { bool ret = m.find(val) == m.end(); m[val].push_back(nums.size()); nums.push_back({val, m[val].size() - 1}); return ret; } bool remove(int val) { bool ret = m.find(val) != m.end(); if(ret){ pair <int, int> last = nums.back(); m[last.first][last.second] = m[val].back(); nums[m[val].back()] = last; m[val].pop_back(); if(m[val].empty())m.erase(val); nums.pop_back(); } return ret; } int getRandom() { return nums[rand() % nums.size()].first; } }; main(){ RandomizedCollection ob; ob.insert(10); ob.insert(35); ob.insert(20); ob.insert(40); cout << (ob.getRandom()) << endl; ob.remove(20); cout << (ob.getRandom()) << endl; }
Input
Insert 10, 35, 20, 40, then get one random number, say 40, then remove 20, again get random element, that is say 35.
Output
40 35
Advertisements