diff --git a/design-hashmap.py b/design-hashmap.py new file mode 100644 index 00000000..80c2888c --- /dev/null +++ b/design-hashmap.py @@ -0,0 +1,48 @@ +# time O(1) +# space O(n) + +class Node: + def __init__(self, key=-1,val=-1, next=None): + self.key=key + self.val=val + self.next = next + +class MyHashMap: +# key | value +# 100 | 1 +# 1100 | 2 +# 100 % 1000 = 100 +# 1100 %1000 = 100 +# key | value +# 100 | (100,1)->(1100,2) + def __init__(self): + self.map = [Node() for i in range(1000)] + + def hash(self,key): + return key % len(self.map) + + def put(self, key: int, value: int) -> None: + cur = self.map[self.hash(key)] + while cur.next: + if cur.next.key == key: + cur.next.val = value + return + cur = cur.next + cur.next = Node(key,value) + + def get(self, key: int) -> int: + cur = self.map[self.hash(key)] + while cur: + if cur.key == key: + return cur.val + cur = cur.next + + return -1 + + def remove(self, key: int) -> None: + cur = self.map[self.hash(key)] + while cur and cur.next: + if cur.next.key == key: + cur.next = cur.next.next + return + cur = cur.next diff --git a/queue-using-stacks.py b/queue-using-stacks.py new file mode 100644 index 00000000..ff7f1eb4 --- /dev/null +++ b/queue-using-stacks.py @@ -0,0 +1,39 @@ +# O(n) time +# O(n) space + +class MyQueue: + + def __init__(self): + self.inStack = [] # stores all newly pushed elements + self.outStack=[] # used for popping and peeking elements in fifo order + + def push(self, x: int) -> None: + self.inStack.append(x) + + def pop(self) -> int: + if not self.outStack: + while self.inStack: + self.outStack.append(self.inStack.pop()) + + return self.outStack.pop() + + def peek(self) -> int: + if not self.outStack: + while self.inStack: + self.outStack.append(self.inStack.pop()) + + return self.outStack[-1] + + def empty(self) -> bool: + if len(self.inStack)==0 and len(self.outStack)==0: + return True + else: + return False + + +# 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