diff --git a/2stacks_queue.py b/2stacks_queue.py new file mode 100644 index 00000000..a41d7362 --- /dev/null +++ b/2stacks_queue.py @@ -0,0 +1,44 @@ +""" +// Time Complexity : o(1) for for all operations except pop which is amortized o(1) +// Space Complexity : o(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : None + +""" + + +class MyQueue: + + def __init__(self): + self.in_stack = [] + self.out_stack = [] + + def push(self, x: int) -> None: + self.in_stack.append(x) + + def pop(self) -> int: + if not self.in_stack and not self.out_stack: + return -1 + if not self.out_stack: + while self.in_stack: + self.out_stack.append(self.in_stack.pop()) + return self.out_stack.pop() + + def peek(self) -> int: + if not self.in_stack and not self.out_stack: + return -1 + if not self.out_stack: + return self.in_stack[0] + if self.out_stack: + return self.out_stack[-1] + + def empty(self) -> bool: + return len(self.in_stack) == 0 and len(self.out_stack) == 0 + + +# 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() diff --git a/hashmap.py b/hashmap.py new file mode 100644 index 00000000..1721137e --- /dev/null +++ b/hashmap.py @@ -0,0 +1,46 @@ +""" +// Time Complexity : o(1) for for all operations +// Space Complexity : o(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : null checks did not check instead of == None in python and it failed for get(0) + +""" + + +class MyHashMap: + + def __init__(self): + self.map = [None] * 1000 + self.divisor = 1000 + + def put(self, key: int, value: int) -> None: + main_index = key % self.divisor + if not self.map[main_index]: + self.map[main_index] = [None] * 1000 if main_index != 0 else [None] * 1001 + secondary_index = key // self.divisor + self.map[main_index][secondary_index] = value + + def get(self, key: int) -> int: + main_index = key % self.divisor + if not self.map[main_index]: + return -1 + secondary_index = key // self.divisor + if self.map[main_index][secondary_index] == None: + return -1 + return self.map[main_index][secondary_index] + + def remove(self, key: int) -> None: + main_index = key % self.divisor + if not self.map[main_index]: + return + secondary_index = key // self.divisor + if self.map[main_index][secondary_index] == None: + return + self.map[main_index][secondary_index] = None + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key)