Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions hash_set.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
// Time Complexity :
add - o(n)
remove - o(n)
contains - 0(n)
// Space Complexity : o(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : yes, made an error in contains but managed to correct the error
"""


class Node:
def __init__(self, val, nxt=None, prev=None):
self.val = val
self.next = nxt
self.prev = prev


class MyHashSet:

def __init__(self):
self.prime_mod = 997
self.set_list = [None] * self.prime_mod

def add(self, key: int) -> None:
index = key % self.prime_mod
val_node = Node(key)
if ptr := self.set_list[index]:
while ptr:
if ptr.val == key:
return
if not ptr.next:
ptr.next = val_node
val_node.prev = ptr
return
ptr = ptr.next
else:
dummy = Node(None)
dummy.next = val_node
val_node.prev = dummy
self.set_list[index] = dummy

def remove(self, key: int) -> None:
index = key % self.prime_mod
if head := self.set_list[index]:
ptr = head.next
while ptr:
if ptr.val == key:
prev = ptr.prev
nxt = ptr.next
prev.next = nxt
if nxt:
nxt.prev = prev
if prev == head and not head.next:
self.set_list[index] = None
return
ptr = ptr.next

def contains(self, key: int) -> bool:
index = key % self.prime_mod
if head := self.set_list[index]:
ptr = head.next
while ptr:
if ptr.val == key:
return True
ptr = ptr.next
return False
36 changes: 36 additions & 0 deletions min_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
// Time Complexity :
push - o(1)
pop - o(1)
top - 0(1)
get_min - o(1)
// Space Complexity : o(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : yes, knew I had to use two stacks but had doubts with my approach, had to look at editorial to
confirm my approach was right
"""


class MinStack:

def __init__(self):
self.stack = []
self.mins = []

def push(self, val: int) -> None:
self.stack.append(val)
if not self.mins:
self.mins.append(val)
elif self.mins[-1] >= val:
self.mins.append(val)

def pop(self) -> None:
element = self.stack.pop()
if self.mins[-1] == element:
self.mins.pop()

def top(self) -> int:
return self.stack[-1]

def getMin(self) -> int:
return self.mins[-1]