diff --git a/Exercise_1.py b/Exercise_1.py new file mode 100644 index 00000000..2027b763 --- /dev/null +++ b/Exercise_1.py @@ -0,0 +1,41 @@ +# Queues using the stack + +#Time complexity O(1) for each operation, SpaceComplexity O(n) where n is the number of elemnts present +# Used 2 stacks, when input is coming keep loadin in satck 1, when popnor peek is called it is removed from stack 2 +# stack 2 is filled when it is empty, all the elemnts from the stack 1 is moved to stack to such that top element in +# stack 2 move to bottom on stack 1, giving us FIFO when removing elemnts from stack 2 + +class MyQueue: + + def __init__(self): + self.enteringStack = [] + self.outgoingStack = [] + + def push(self, x: int) -> None: + self.enteringStack.append(x) + + def pop(self) -> int: + self.readjustStacksIfNeeded() + return self.outgoingStack.pop() + + def peek(self) -> int: + self.readjustStacksIfNeeded() + return self.outgoingStack[-1] + + def empty(self) -> bool: + return (len(self.enteringStack) + len(self.outgoingStack)) == 0 + + def readjustStacksIfNeeded(self): + #Because of the constraint pop and ppek are valid, no need to check if enteringStack is empty + #reload the outgoingStack if enteringStack is not empty + if len(self.outgoingStack) == 0: + while len (self.enteringStack) > 0: + self.outgoingStack.append(self.enteringStack.pop()) + + +# Your MyQueue object will be instantiated and called as such: +# obj = MyQueue() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.peek() +# param_4 = obj.empty() \ No newline at end of file diff --git a/Exercise_2.py b/Exercise_2.py new file mode 100644 index 00000000..8875e013 --- /dev/null +++ b/Exercise_2.py @@ -0,0 +1,45 @@ +class MyHashMap: + + def __init__(self): + self.primaryArray = [None]*1001 + + def put(self, key: int, value: int) -> None: + primaryHash = self.primaryHash(key) + if self.primaryArray[primaryHash] == None: + # since we have to return -1 if key doesn't exist, creating the array initialized to -1 + # this will automatically return -1 for keys that are not present + self.primaryArray[primaryHash] = [-1]*1000 + + secondarHash = self.secondaryHash(key) + self.primaryArray[primaryHash][secondarHash] = value + + def get(self, key: int) -> int: + primaryHash = self.primaryHash(key) + if self.primaryArray[primaryHash] == None: + return -1 + else: + secondaryHash = self.secondaryHash(key) + return self.primaryArray[primaryHash][secondaryHash] + + def remove(self, key: int) -> None: + primaryHash = self.primaryHash(key) + if self.primaryArray[primaryHash] == None: + return + else: + secondaryHash = self.secondaryHash(key) + self.primaryArray[primaryHash][secondaryHash] = -1 + + def primaryHash(self, key): + return key//1000 + + def secondaryHash(self,key): + return key%1000 + + + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) \ No newline at end of file