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
39 changes: 39 additions & 0 deletions HashSet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Time Complexity : O(1)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : two level bucket structure (primary -> secondary) with boolean arrays for constant time access.

class MyHashSet:
def __init__(self):
self.primaryBucketSize = 1000
self.secondaryBucketSize = 1001 # for division edge case
self.storage = [[] for _ in range(self.primaryBucketSize)]

def getPrimaryHash(self, key: int) -> int:
return key % self.primaryBucketSize

def getSecondaryHash(self, key: int) -> int:
return key // self.secondaryBucketSize

def add(self, key: int) -> None:
primaryHash = self.getPrimaryHash(key)
if self.storage[primaryHash] == []:
self.storage[primaryHash] = [False] * (self.secondaryBucketSize)

secondaryHash = self.getSecondaryHash(key)
self.storage[primaryHash][secondaryHash] = True

def remove(self, key: int) -> None:
primaryHash = self.getPrimaryHash(key)
if not self.storage[primaryHash]:
return
secondaryHash = self.getSecondaryHash(key)
self.storage[primaryHash][secondaryHash] = False

def contains(self, key: int) -> bool:
primaryHash = self.getPrimaryHash(key)
if not self.storage[primaryHash]:
return False
secondaryHash = self.getSecondaryHash(key)
return self.storage[primaryHash][secondaryHash]
28 changes: 28 additions & 0 deletions MinStack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Time Complexity : O(1)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Only when a new min appears, we store the previous min in the stack,
# so that when the current min is removed, we can restore the old one in constant time.

class MinStack:

def __init__(self):
self.stack = []
self.min = float('inf')

def push(self, val: int) -> None:
if val <= self.min:
self.stack.append(self.min)
self.min = val
self.stack.append(val)

def pop(self) -> None:
if self.min == self.stack.pop():
self.min = self.stack.pop()

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

def getMin(self) -> int:
return self.min