From c15df81f741d236190a3127e6ff203e1bdb65e1d Mon Sep 17 00:00:00 2001 From: sainaga00 Date: Tue, 3 Feb 2026 15:01:12 -0500 Subject: [PATCH] Add MinStack and HashSet implementations --- designHashSet.py | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ minStack.py | 33 +++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 designHashSet.py create mode 100644 minStack.py diff --git a/designHashSet.py b/designHashSet.py new file mode 100644 index 00000000..9c42388c --- /dev/null +++ b/designHashSet.py @@ -0,0 +1,51 @@ +# Time Complexity: O(1) average +# Space Complexity: O(n) where n is the number of keys +# Did this code successfully run on LeetCode: Yes +# Any problem faced while coding: No +# Approach: Used chaining with linked list for collision + + +class Node: + def __init__(self,key): + self.key = key + self.next = None + +class MyHashSet: + def __init__(self): + self.hset = [Node(0) for i in range(10**4)] + + def add(self, key: int) -> None: + curr = self.hset[key % len(self.hset)] + while curr.next: + if curr.next.key == key: + return + curr = curr.next + curr.next = Node(key) + + def remove(self, key: int) -> None: + curr = self.hset[key % len(self.hset)] + while curr.next: + if curr.next.key == key: + curr.next = curr.next.next + return + curr = curr.next + + def contains(self, key: int) -> bool: + curr = self.hset[key % len(self.hset)] + while curr.next: + if curr.next.key == key: + return True + curr = curr.next + return False + + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) + + + + diff --git a/minStack.py b/minStack.py new file mode 100644 index 00000000..8974a5e5 --- /dev/null +++ b/minStack.py @@ -0,0 +1,33 @@ +# Time Complexity : O(1) for all operations +# Space Complexity : O(n) -> n is no of elements in stack +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Store each value along with the minimum value seen so far at that point. + + +class MinStack: + def __init__(self): + self.st = [] + + def push(self, val: int) -> None: + curr_min = self.getMin() + if curr_min == None or curr_min > val: + curr_min = val + self.st.append([val,curr_min]) + + def pop(self) -> None: + self.st.pop() + + def top(self) -> int: + return self.st[-1][0] + + def getMin(self) -> int: + return self.st[-1][1] if self.st else None + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(val) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() \ No newline at end of file