# Insert Delete GetRandom O(1) in Python

PythonServer Side ProgrammingProgramming

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

Let us see the following implementation to get better understanding −

import random
class RandomizedSet(object):
def __init__(self):
"""
"""
self.present = {}
self.elements = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
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):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
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):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.elements)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

## Input

["RandomizedSet","insert","remove","insert","getRandom","remove","insert","getRandom"]
[[],[1],[2],[2],[],[1],[2],[]]

## Output

[null,true,false,true,1,true,false,2]
Published on 17-Mar-2020 06:12:18