Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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) in Python
Suppose we have a data structure that supports all following operations in average O(1) time.
insert(val) − This will Insert an item val to the set if that is not already present.
remove(val) − This will remove an item val from the set if it presents.
getRandom − This will return a random element from current set of elements. Each element must have the same probability of being returned.
To solve this, we will follow these steps −
For the initialization, define a parent map, and elements array
-
For the insert() function, it will take val as input
if val is not present in parent map, or parent[val] = 0, then insert val into elements, and set parent[val] := 1, and return true
return false
For the remove() method, it will take val to remove
if val is not present in parent map, or parent[val] = 0, then return false
set parent[val] := 0
index := index of val in elements array
-
if index is not same as length of elements – 1
temp := last element of elements
set last element of elements := val
set elements[index] := temp
delete last element of elements
The getRandom() method will return any random value present in elements array
Example(Python)
Let us see the following implementation to get a better understanding −
import random
class RandomizedSet(object):
def __init__(self):
self.present = {}
self.elements = []
def insert(self, val):
if val not in self.present or self.present[val] == 0:
self.elements.append(val)
self.present[val] = 1
return True
return False
def remove(self, val):
if val not in self.present or self.present[val] == 0:
return False
self.present[val] = 0
index = self.elements.index(val)
if index!=len(self.elements)-1:
temp = self.elements[-1]
self.elements[-1] = val
self.elements[index]=temp
self.elements.pop()
return True
def getRandom(self):
return random.choice(self.elements)
ob = RandomizedSet()
print(ob.insert(1))
print(ob.remove(2))
print(ob.insert(2))
print(ob.getRandom())
print(ob.remove(1))
print(ob.insert(2))
print(ob.getRandom())
Input
Initialize the class, then call the insert(), remove(), getRandom() functions. See the implementation.
Output
True False True 2 True False 2