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
48 changes: 48 additions & 0 deletions hashset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Uses linked lists to handle hash collisions across 1000 buckets.
# Each bucket has a dummy head node; add/remove/contains traverse the chain at key % 1000.

# Time Complexity: average per operation O(1)
# Space Complexity: O(n + k)

"""
@author: chinmayprajapati
"""

class ListNode:
def __init__(self, key = -1, next = None):
self.key = key
self.next = next

class MyHashSet:

def __init__(self):
self.map = [ListNode() for i in range(1000)]

def hash(self, key):
return key % len(self.map)

def add(self, key: int) -> None:
current = self.map[self.hash(key)]
while current.next:
if current.next.key == key:
return
current = current.next
current.next = ListNode(key)


def remove(self, key: int) -> None:
current = self.map[self.hash(key)]
while current.next:
if current.next.key == key:
current.next = current.next.next
return
current = current.next


def contains(self, key: int) -> bool:
current = self.map[self.hash(key)].next
while current:
if current.key == key:
return True
current = current.next
return False
32 changes: 32 additions & 0 deletions minstack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Time Complexity: O(1)
# Space Complexity: O(n)
# Two stacks: one for values, one tracking the running min at each push

"""
@author: chinmayprajapati
"""

class MinStack:

def __init__(self):
self.minstack = list()
self.stack = list()

def push(self, val: int) -> None:
self.stack.append(val)
if not self.minstack:
self.minstack.append(val)
else:
self.minstack.append(min(self.minstack[-1],val))

def pop(self) -> None:
self.stack.pop()
self.minstack.pop()

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

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