🎉 One-stop destination for all your technical interview Preparation 🎉
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.MinStack* obj = new MinStack();
obj->push(val);
obj->pop();
int param_3 = obj->top();
int param_4 = obj->getMin();
INT_MAX
to min stack in declaration.push
operation:
pop
operation:
top
operation:
getMin
operation:
class MinStack {
vector<int> st;
vector<int> mnStack;
public:
MinStack() {
mnStack.push_back(INT_MAX);
}
void push(int val) {
st.push_back(val);
mnStack.push_back(min(val,mnStack.back()));
}
void pop() {
st.pop_back();
mnStack.pop_back();
}
int top() {
return st.back();
}
int getMin() {
return mnStack.back();
}
};
push
operation:
pop
operation:
class MinStack{
vector<int> st;
int minElem;
public:
MinStack() { minElem = INT_MAX; }
void push(int val){
if(val<=minElem){
st.push_back(minElem);
minElem = val;
}
st.push_back(val);
}
void pop(){
int top = st.back();
st.pop_back();
if (top == minElem){
minElem = st.back();
st.pop_back();
}
}
int top() { return st.back(); }
int getMin() { return minElem; }
};
class MinStack{
vector<pair<int, int>> st;
public:
MinStack() {}
void push(int val){
if (st.empty())
st.push_back({val, val});
else
st.push_back({val, min(st.back().second, val)});
}
void pop() { st.pop_back(); }
int top() { return st.back().first; }
int getMin() { return st.back().second; }
};