diff --git a/Exercise_1.py b/Exercise_1.py new file mode 100644 index 00000000..11a7742b --- /dev/null +++ b/Exercise_1.py @@ -0,0 +1,37 @@ +#Design HashSet + +# use an array of size 1000, with each elemnt can have another array of 1000 giving us range 10^6 key limit +# Using the hashing functions as // and % for keeps the time constraints for each operations O(1) +# as only when collision happens new sub array is initialized, and that to of max length 1000 so avg case is O1 +# space complexity will be in worst case O(n) where n is the keys added +class MyHashSet: + + def __init__(self): + self.primaryArr = [False] * 1001 + + def add(self, key: int) -> None: + primaryHash = self.primaryHash(key) + if self.primaryArr[primaryHash] == False: + self.primaryArr[primaryHash] = [False]*1000 + secondaryHash = self.secondaryHash(key) + self.primaryArr[primaryHash][secondaryHash] = True + + def remove(self, key: int) -> None: + primaryHash = self.primaryHash(key) + secondaryHash = self.secondaryHash(key) + if self.primaryArr[primaryHash]: + self.primaryArr[primaryHash][secondaryHash] = False + + def contains(self, key: int) -> bool: + primaryHash = self.primaryHash(key) + secondaryHash = self.secondaryHash(key) + if self.primaryArr[primaryHash]: + return self.primaryArr[primaryHash][secondaryHash] + return False + + def primaryHash(self, key): + return key//1000 + + def secondaryHash(self, key): + return key%1000 + diff --git a/Exercise_2.py b/Exercise_2.py new file mode 100644 index 00000000..4ae341ab --- /dev/null +++ b/Exercise_2.py @@ -0,0 +1,49 @@ +#Design MinStack + +# I'm using 2 stack approach, where 1st stack is saving all the items, while the 2nd is saving only +# if the new item is smaller than the last minimum item. Then during the pop we check if the removed item +# from the stack of all items is same as the min, then remove the last elemnt from 2nd stacka and set the minValue +# to be the top value from the 2nd array. This gives is O(1) time complexity for all operations and O(n) space complexity + +class MinStack: + + def __init__(self): + self.allItems = [] + self.minOrderedItems = [] + self.minItem = None + + def push(self, val: int) -> None: + self.allItems.append(val) + if self.minItem == None or self.minItem >= val: + self.minItem = val + self.minOrderedItems.append(val) + # elif self.minItem >= val : + # self.minItem = val + # self.minOrderedItems.append(val) + # else: + # return + + def pop(self) -> None: + poppedItem = self.allItems.pop() + if poppedItem == self.minItem: + self.minOrderedItems.pop() + if len(self.minOrderedItems) > 0: + self.minItem = self.minOrderedItems[-1] + else: + self.minItem = None + + def top(self) -> int: + return self.allItems[-1] + + def getMin(self) -> int: + return self.minItem + + + + +# 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() \ No newline at end of file