|
| 1 | +""" |
| 2 | +Description: |
| 3 | +Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. |
| 4 | +
|
| 5 | +Operations: |
| 6 | +1. push(x) -> Push element x onto stack. |
| 7 | +2. pop() -> Removes the element on top of the stack. |
| 8 | +3. top() -> Get the top element. |
| 9 | +4. getMin() -> Retrieve the minimum element in the stack. |
| 10 | +
|
| 11 | +Example: |
| 12 | + min_stack = MinStack() |
| 13 | + min_stack.push(-2) |
| 14 | + min_stack.push(0) |
| 15 | + min_stack.push(-3) |
| 16 | + min_stack.getMin() # returns -3 |
| 17 | + min_stack.pop() |
| 18 | + min_stack.top() # returns 0 |
| 19 | + min_stack.getMin() # returns -2 |
| 20 | +
|
| 21 | +Time Complexity: |
| 22 | +- push: O(1) |
| 23 | +- pop: O(1) |
| 24 | +- top: O(1) |
| 25 | +- getMin: O(1) |
| 26 | +
|
| 27 | +Space Complexity: |
| 28 | +- O(n) extra space for the min_stack |
| 29 | +""" |
| 30 | + |
| 31 | +class MinStack: |
| 32 | + def __init__(self): |
| 33 | + """ |
| 34 | + Initialize two stacks: |
| 35 | + - main_stack: stores all elements |
| 36 | + - min_stack: stores the current minimum element at each level |
| 37 | + """ |
| 38 | + self.main_stack = [] |
| 39 | + self.min_stack = [] |
| 40 | + |
| 41 | + def push(self, x: int) -> None: |
| 42 | + """ |
| 43 | + Push element x onto stack. |
| 44 | +
|
| 45 | + Args: |
| 46 | + x (int): Element to push |
| 47 | + """ |
| 48 | + self.main_stack.append(x) |
| 49 | + # Push to min_stack if it's empty or x is <= current minimum |
| 50 | + if not self.min_stack or x <= self.min_stack[-1]: |
| 51 | + self.min_stack.append(x) |
| 52 | + |
| 53 | + def pop(self) -> None: |
| 54 | + """ |
| 55 | + Removes the element on top of the stack. |
| 56 | + """ |
| 57 | + if self.main_stack: |
| 58 | + val = self.main_stack.pop() |
| 59 | + if val == self.min_stack[-1]: |
| 60 | + self.min_stack.pop() |
| 61 | + |
| 62 | + def top(self) -> int: |
| 63 | + """ |
| 64 | + Get the top element of the stack. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + int: Top element if stack is not empty, else None |
| 68 | + """ |
| 69 | + return self.main_stack[-1] if self.main_stack else None |
| 70 | + |
| 71 | + def getMin(self) -> int: |
| 72 | + """ |
| 73 | + Retrieve the minimum element in the stack. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + int: Minimum element if stack is not empty, else None |
| 77 | + """ |
| 78 | + return self.min_stack[-1] if self.min_stack else None |
| 79 | + |
| 80 | + |
| 81 | +# Example Usage |
| 82 | +if __name__ == "__main__": |
| 83 | + min_stack = MinStack() |
| 84 | + min_stack.push(-2) |
| 85 | + min_stack.push(0) |
| 86 | + min_stack.push(-3) |
| 87 | + print("Current Min:", min_stack.getMin()) # Output: -3 |
| 88 | + min_stack.pop() |
| 89 | + print("Top Element:", min_stack.top()) # Output: 0 |
| 90 | + print("Current Min:", min_stack.getMin()) # Output: -2 |
0 commit comments