diff --git a/hashmap.py b/hashmap.py new file mode 100644 index 00000000..c58030ce --- /dev/null +++ b/hashmap.py @@ -0,0 +1,61 @@ +# Problem: Design HashMap +# Time Complexity: O(1) average for put, get, remove (O(n) worst case due to chaining) +# Space Complexity: O(n) where n is number of keys inserted +# Did this code successfully run on Leetcode: YES +# Any problem you faced while coding this: Understanding linked list chaining approach + +class MyHashMap: + class Node: + def __init__(self, key=None, value=None, next=None): + self.key = key + self.value = value + self.next = next + + def __init__(self): + self.arr = [None] * 10000 + + def hash_func(self, key): + return key % 10000 + + def find(self, head, key): + prev = None + curr = head + while curr is not None and curr.key != key: + prev = curr + curr = curr.next + return prev + + def put(self, key, value): + hash_val = self.hash_func(key) + if self.arr[hash_val] is None: + self.arr[hash_val] = self.Node(-1, -1, None) + prev = self.find(self.arr[hash_val], key) + if prev.next is None: + prev.next = self.Node(key, value, None) + else: + prev.next.value = value + + def get(self, key): + hash_val = self.hash_func(key) + if self.arr[hash_val] is None: + return -1 + prev = self.find(self.arr[hash_val], key) + if prev.next is None: + return -1 + return prev.next.value + + def remove(self, key): + hash_val = self.hash_func(key) + if self.arr[hash_val] is None: + return + prev = self.find(self.arr[hash_val], key) + if prev.next is None: + return + prev.next = prev.next.next + + +# 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 diff --git a/queue-using-stacks.py b/queue-using-stacks.py new file mode 100644 index 00000000..1d456f83 --- /dev/null +++ b/queue-using-stacks.py @@ -0,0 +1,42 @@ +# Problem: Implement Queue using Stacks +# Time Complexity: +# push: O(1) - always +# pop: O(1) amortized - O(n) only when outStack is empty, but each element moved once in its lifetime +# peek: O(1) amortized - same reasoning as pop +# empty: O(1) - always +# Space Complexity: O(n) where n is number of elements in the queue +# Did this code successfully run on Leetcode: YES +# Any problem you faced while coding this: No + + + + +class MyQueue(object): + + def __init__(self): + self.inStack = [] + self.outStack = [] + + def push(self, x): + self.inStack.append(x) + + def pop(self): + self.peek() + return self.outStack.pop() + + def peek(self): + if len(self.outStack) == 0: + while len(self.inStack) > 0: + self.outStack.append(self.inStack.pop()) + return self.outStack[-1] + + def empty(self): + return len(self.inStack) == 0 and len(self.outStack) == 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() \ No newline at end of file