diff --git a/Queue_using_stacks.py b/Queue_using_stacks.py new file mode 100644 index 00000000..57d33b38 --- /dev/null +++ b/Queue_using_stacks.py @@ -0,0 +1,34 @@ +// Time Complexity : O(N) +// Space Complexity : O(N) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +#I have used two stacks to push all the elements to stack2 when peek method is called and return the top element. +#Pop() calls peek() first and then returns top element from stack2. + + +class MyQueue: + def __init__(self): + self.stack1 = [] + self.stack2 = [] + + def push(self, x:int) -> None: + self.stack1.append(x) + + def peek(self) -> int: + if self.stack2 == []: + while self.stack1: + self.stack2.append(self.stack1.pop()) + return self.stack2[-1] + + + def pop(self) -> int: + self.peek() + return self.stack2.pop() + + def empty(self) -> bool: + if not self.stack1 and not self.stack2: + return True + return False \ No newline at end of file diff --git a/implement_HashMap.py b/implement_HashMap.py new file mode 100644 index 00000000..b6a3686e --- /dev/null +++ b/implement_HashMap.py @@ -0,0 +1,67 @@ +// Time Complexity : O(1) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach in three sentences only +#I have designed HashMap using LinkedList that is linear chaining. + +class MyHashMap: + + class Node: + + def __init__(self, key, value): + self.key = key + self.value = value + self.next = None + + def __init__(self): + self.data = 1000 + self.storage = [None] * self.data + + def hash1(self, key): + index = key % self.data + return index + + def findPrev(self, head, key): + currentNode = head + prev = None + while currentNode != None and currentNode.key != key: + prev = currentNode + currentNode = currentNode.next + return prev + + def put(self, key:int, value:int) -> None: + data_index = self.hash1(key) + if self.storage[data_index] is None: + self.storage[data_index] = self.Node(-1,-1) + prev = self.findPrev(self.storage[data_index], key) + if prev.next is None: + prev.next = self.Node(key, value) + else: + prev.next.value = value + + + def remove(self, key:int) -> None: + data_index = self.hash1(key) + if self.storage[data_index] is None: + return + prev = self.findPrev(self.storage[data_index], key) + if prev.next == None: + return + temp = prev.next + prev.next = prev.next.next + temp.next = None + + def get(self, key:int) -> int: + data_index = self.hash1(key) + if self.storage[data_index] is None: + return -1 + prev = self.findPrev(self.storage[data_index], key) + if prev.next == None: + return -1 + return prev.next.value + + + \ No newline at end of file