diff --git a/Hashmap.py b/Hashmap.py new file mode 100644 index 00000000..1c22fc32 --- /dev/null +++ b/Hashmap.py @@ -0,0 +1,67 @@ +#// Time Complexity : Averge of O(1) unless everything ends up in one bucket. +#// Space Complexity : O(N) +#// Did this code successfully run on Leetcode : Yes +#// Any problem you faced while coding this : Had mutliple issues when converting theory concept to coding like referncing to one with 10000 copies of it. + + +#// Your code here along with comments explaining your approach +#using array of buckets and small list to store collions. +#used modulo function as hashing function to find key + +class MyHashMap(object): + + def __init__(self): + self.size = 1001 + self.table = [[] for _ in range(self.size)] + + def _hash(self,key): + return key % self.size + + def put(self, key, value): + """ + :type key: int + :type value: int + :rtype: None + """ + index = self._hash(key) + bucket = self.table[index] + + for pair in bucket: + if pair[0] == key: + pair[1] = value + return + bucket.append([key,value]) + + + def get(self, key): + """ + :type key: int + :rtype: int + """ + index = self._hash(key) + bucket = self.table[index] + + for pair in bucket: + if pair[0] == key: + return pair[1] + return -1 + + def remove(self, key): + """ + :type key: int + :rtype: None + """ + index = self._hash(key) + bucket = self.table[index] + + for i,pair in enumerate(bucket): + if pair[0] == key: + bucket.pop(i) + return + + +# 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..3cc4a1d2 --- /dev/null +++ b/Queue_using_stacks.py @@ -0,0 +1,52 @@ +#// Time Complexity : Amortised O(1), Worst case 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 +# Use one in stock to push and other out stack to pop. +# When pop or peek is called, check if out stack is empty. +# If it is empty then pop all elements from in stack and push to out stack. + +class MyQueue(object): + + def __init__(self): + self.in_stack = [] + self.out_stack = [] + + + def push(self, x): + """ + :type x: int + :rtype: None + """ + self.in_stack.append(x) + + def pop(self): + """ + :rtype: int + """ + self.peek() + return self.out_stack.pop() + + def peek(self): + """ + :rtype: int + """ + if not self.out_stack: + while self.in_stack: + self.out_stack.append(self.in_stack.pop()) + return self.out_stack[-1] + + def empty(self): + """ + :rtype: bool + """ + return not self.out_stack and not self.in_stack + +# obj = MyQueue() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.peek() +# param_4 = obj.empty() \ No newline at end of file