Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2275 from solairerove/main
Browse files Browse the repository at this point in the history
Create: 380-Insert-Delete-Getrandom-O1.py
  • Loading branch information
MHamiid authored Feb 26, 2023
2 parents b9f9132 + ef86ecb commit 1b316a4
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions python/0380-insert-delete-getrandom-o1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from random import choice


class RandomizedSet:

def __init__(self):
self.dict = {}
self.list = []

def insert(self, val: int) -> bool:
if val in self.dict:
return False

self.dict[val] = len(self.list)
self.list.append(val)

return True

def remove(self, val: int) -> bool:
if val not in self.dict:
return False

idx, last_element = self.dict[val], self.list[-1]
self.list[idx], self.dict[last_element] = last_element, idx
self.list.pop()
del self.dict[val]

return True

def getRandom(self) -> int:
return choice(self.list)

0 comments on commit 1b316a4

Please sign in to comment.