Day 10 of 30-Day LeetCode Challenge

Aanchal Patial
1 min readApr 15, 2020

--

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) — Push element x onto stack.
  • pop() — Removes the element on top of the stack.
  • top() — Get the top element.
  • getMin() — Retrieve the minimum element in the stack.

class MinStack {
public:
/** initialize your data structure here. */
stack<int> stck, minStck;

MinStack() {

}

void push(int x) {
if(stck.empty()){
stck.push(x);
minStck.push(x);
}else{
stck.push(x);
if(x<=minStck.top()){
minStck.push(x);
}
}



}

void pop() {
if(minStck.top()==stck.top()){
minStck.pop();
}
stck.pop();

}

int top() {
return stck.top();
}

int getMin() {
return minStck.top();
}
};

/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/

--

--

Aanchal Patial

We never really grow up, we only learn how to act in public