Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.void push(int val) pushes the element val onto the stack.void pop() removes the element on the top of the stack.int top() gets the top element of the stack.int getMin() retrieves the minimum element in the stack.You must implement a solution with O(1) time complexity for each function.
Example 1:
Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2
Constraints:
-231 <= val <= 231 - 1pop, top and getMin operations will always be called on non-empty stacks.3 * 104 calls will be made to push, pop, top, and getMin.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a stack of items where you can add, remove, and look at the top item whenever you want, but you also need to instantly know the smallest item currently in the stack. The brute force approach involves searching through the entire collection of items from scratch every single time someone asks for the smallest one.
Here's how the algorithm would work step-by-step:
class MinStack:
def __init__(self):
self.storage_stack = []
def push(self, number_value):
self.storage_stack.append(number_value)
def pop(self):
self.storage_stack.pop()
def top(self):
return self.storage_stack[-1]
def getMin(self):
# Scan all elements since we need the minimum without a tracking data structure
current_minimum = self.storage_stack[0]
for stack_item in self.storage_stack:
# Compare each item to find the absolute lowest value currently stored
if stack_item < current_minimum:
current_minimum = stack_item
return current_minimumThe optimal strategy involves using a companion tracker that remembers the smallest item seen so far at every single level of our main storage pile. By pairing each new item with the current minimum at the moment it arrives, we can instantly know the smallest item without ever having to search through the pile.
Here's how the algorithm would work step-by-step:
class MinStack:
def __init__(self):
self.storage_pile = []
def push(self, new_item):
# Pair the new item with the current minimum to remember historical minimums at every level.
current_minimum = min(new_item, self.storage_pile[-1][1]) if self.storage_pile else new_item
self.storage_pile.append((new_item, current_minimum))
def pop(self):
# Removing the top element automatically restores the previous minimum safely kept underneath.
self.storage_pile.pop()
def top(self):
return self.storage_pile[-1][0]
def get_min(self):
# Looking at the attached note on the top item yields the minimum in constant time.
return self.storage_pile[-1][1]| Case | How to Handle |
|---|---|
| Stack operations performed on an empty stack | Methods like pop, top, and getMin should not be called on an empty stack according to problem constraints, but guard clauses can prevent underflow errors. |
| Stack containing only a single element | The single element automatically becomes both the top and the minimum value. |
| Pushing multiple identical minimum values consecutively | The minimum tracking structure must record duplicates so that popping one still leaves the correct minimum active. |
| Pushing strictly decreasing or strictly increasing sequences | An auxiliary stack approach must push a new minimum on every decrease and ignore non-minimums to maintain constant time. |
| Handling extreme integer values such as Integer.MIN_VALUE and Integer.MAX_VALUE | Standard integer types handle these bounds natively without causing overflow issues during simple comparisons. |
| Handling a large number of push operations reaching scale limits | Dynamic array or linked list backing stores grow efficiently to accommodate extensive operations without manual resizing bugs. |
| Mixed sequence of pushes and pops with alternating minimums | The secondary minimum stack pops its top element synchronously whenever the primary stack pops, keeping the current minimum accurate. |
| Inputs containing negative numbers, zeros, and positive numbers | Comparison logic relies on relational operators rather than absolute magnitudes, making sign transitions seamless. |