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
47 changes: 47 additions & 0 deletions MinStack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
''' Time Complexity : O(1) for all the operations
Space Complexity : O(n) ; where n is no of elements and we are maintaining the stack
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Your code here along with comments explaining your approach

Approach : Maintaining the one to one mapping between stack and min_stack,
to keep the track of previous minimums.
'''


class MinStack:

def __init__(self):
self.stack = []
self.min_stack = []
self.min=float("infinity")

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

def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
if self.min_stack:
self.min = self.min_stack[-1]
else:
self.min = float("infinity")


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

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


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
51 changes: 51 additions & 0 deletions MyHashSet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
''' Time Complexity : O(1) for all the operations
Space Complexity : O(n) ; where n is no of elements will be added to the hashset
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No


Your code here along with comments explaining your approach

Approach : First, initialized the storage with primary array and boolean array, then
implemented the first and second hash function.
'''

class MyHashSet:

def __init__(self):
self.bucket = 1000
self.bucketItem = 1001
self.storage = [[] for i in range(self.bucket)]

def add(self, key: int) -> None:

index = key%self.bucket
if self.storage[index] == []:
self.storage[index] = [False for i in range(self.bucketItem)]

index2 = key//self.bucketItem
self.storage[index][index2] = True

def remove(self, key: int) -> None:
index = key%self.bucket
if self.storage[index]:
index2 = key//self.bucketItem
self.storage[index][index2] = False

def contains(self, key: int) -> bool:
index = key%self.bucket
index2 = key//self.bucketItem
if self.storage[index] != []:
return self.storage[index][index2]
else:
return False

obj = MyHashSet()
print(obj.add(1))
print(obj.add(2))
print(obj.contains(1))
print(obj.contains(3))
print(obj.add(2))
print(obj.contains(2))
print(obj.remove(2))
print(obj.contains(2))