O( 1 )✅ | Python (Step by step explanation)
Intuition\nThe MinStack is a data structure that allows for efficient retrieval of the minimum value in a stack at any given moment. This is achieved by maintai
# Intuition\nThe MinStack is a data structure that allows for efficient retrieval of the minimum value in a stack at any given moment. This is achieved by maintaining two stacks: one for the actual elements (the `stack`), and another for the minimum elements (the `minStack`).\n\n# Approach\n1. Initialize two lists (stacks): `stack` for the actual elements and `minStack` for the minimum elements.\n2. When pushing an element into the stack:\n   - Append the element to the `stack`.\n   - Check if `minStack` is not empty. If it\'s not empty, calculate the minimum between the current element and the top element of `minStack`, and append the minimum to `minStack`. This ensures that `minStack` always contains the minimum value in the stack.\n3. When popping an element from the stack:\n   - Pop the element from both `stack` and `minStack`. This maintains the consistency of the two stacks.\n4. To get the top element of the stack, return the last element in `stack`.\n5. To get the minimum value in the stack, return the last element in `minStack`. This allows for a constant-time operation for retrieving the minimum value.\n\n# Complexity\n- Time complexity:\n   - Push: O(1)\n   - Pop: O(1)\n   - Top: O(1)\n   - GetMin: O(1)\n- Space complexity: O(n), where n is the number of elements in the stack.\n\n\n# Code\n```\nclass MinStack:\n\n    def __init__(self):\n        self.stack = []\n        self.minStack = []\n        \n\n    def push(self, val: int) -> None:\n        self.stack.append(val)\n        val = min(val , self.minStack[-1] if self.minStack else val)\n        self.minStack.append(val)\n        \n\n    def pop(self) -> None:\n        self.stack.pop()\n        self.minStack.pop()\n        \n\n    def top(self) -> int:\n        return self.stack[-1]\n        \n\n    def getMin(self) -> int:\n        return self.minStack[-1]\n        \n\n\n# Your MinStack object will be instantiated and called as such:\n# obj = MinStack()\n# obj.push(val)\n# obj.pop()\n# param_3 = obj.top()\n# param_4 = obj.getMin()\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/3129fc43-0e23-4473-8b7e-025808e03744_1697646788.795858.jpeg)\n
['Stack', 'Python3']