|
| 1 | +--- |
| 2 | +comments: true |
| 3 | +difficulty: medium |
| 4 | +# Follow `Topics` tags |
| 5 | +tags: |
| 6 | + - Stack |
| 7 | + - Design |
| 8 | +--- |
| 9 | + |
| 10 | +# [155. Min Stack](https://leetcode.com/problems/min-stack/description/) |
| 11 | + |
| 12 | +## Description |
| 13 | + |
| 14 | +Create a special type of stack called MinStack that, in addition to the usual stack operations, can also return the minimum element currently in the stack — all in constant time (O(1)). |
| 15 | + |
| 16 | +The MinStack class should support the following operations: |
| 17 | + |
| 18 | +1. `MinStack()`: Initializes a new instance of the stack. |
| 19 | + |
| 20 | +2. `void push(int val)`: Adds the given value `val` to the top of the stack. |
| 21 | + |
| 22 | +3. `void pop()`: Removes the top element from the stack. |
| 23 | + |
| 24 | +4. `int top()`: Returns the element currently at the top of the stack. |
| 25 | + |
| 26 | +5. `int getMin()`: Returns the smallest element in the stack at any given time. |
| 27 | + |
| 28 | +Make sure that all these methods run in constant time. |
| 29 | + |
| 30 | + |
| 31 | +**Example 1:** |
| 32 | +``` |
| 33 | +Input: |
| 34 | +["MinStack","push","push","top","push","getMin","pop","top","getMin"] |
| 35 | +[[],[-1],[3],[],[-2],[],[],[],[]] |
| 36 | +
|
| 37 | +Output: [null,null,3,null,-2,null,3,-1] |
| 38 | +
|
| 39 | +Explanation: |
| 40 | +MinStack minStack = new MinStack(); |
| 41 | +minStack.push(-1); |
| 42 | +minStack.push(3); |
| 43 | +minStack.top(); // return 3 |
| 44 | +minStack.push(-2); |
| 45 | +minStack.getMin(); // return -2 |
| 46 | +minStack.pop(); |
| 47 | +minStack.top(); // return 3 |
| 48 | +minStack.getMin(); // return -1 |
| 49 | +``` |
| 50 | + |
| 51 | +**Constraints:** |
| 52 | + |
| 53 | +* `-231 <= val <= 231 - 1` |
| 54 | +* Methods `pop`, `top` and `getMin` operations will always be called on non-empty stacks. |
| 55 | +* At most `3 * 10^4` calls will be made to `push`, `pop`, `top`, and `getMin`. |
| 56 | + |
| 57 | +## Solution |
| 58 | + |
| 59 | +Intuitively remove non-alphanumeric and change others to lowercase. |
| 60 | + |
| 61 | +```java |
| 62 | +``` |
| 63 | + |
| 64 | +```python |
| 65 | +``` |
| 66 | + |
| 67 | +## Complexity |
| 68 | + |
| 69 | +- Time complexity: $$O(1)$$ |
| 70 | +<!-- Add time complexity here, e.g. $$O(n)$$ --> |
| 71 | + |
| 72 | +- Space complexity: $$O(n)$$ |
| 73 | +<!-- Add space complexity here, e.g. $$O(n)$$ --> |
0 commit comments