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.
To maintain the minimum element, we can use an auxiliary stack that keeps track of the minimums. Here’s the idea:
When pushing a new value:
When popping a value:
When retrieving the minimum:
This ensures all operations take constant time O(1).
#include <stack>
#include <stdexcept>
class MinStack {
public:
MinStack() {}
void push(int val) {
mainStack.push(val);
if (minStack.empty() || val <= minStack.top()) {
minStack.push(val);
} else {
minStack.push(minStack.top());
}
}
void pop() {
if (!mainStack.empty()) {
mainStack.pop();
minStack.pop();
}
}
int top() {
if (!mainStack.empty()) {
return mainStack.top();
}
throw std::runtime_error("Stack is empty");
}
int getMin() {
if (!minStack.empty()) {
return minStack.top();
}
throw std::runtime_error("Stack is empty");
}
private:
std::stack<int> mainStack;
std::stack<int> minStack;
};
This implementation ensures all operations have the required O(1) time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?