Skip to content

Commit ea7a31f

Browse files
Update min_stack_o(1).cpp
1 parent da5e64f commit ea7a31f

File tree

1 file changed

+33
-27
lines changed

1 file changed

+33
-27
lines changed

min_stack_o(1).cpp

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,62 @@
11
class MinStack {
22
public:
33
/** initialize your data structure here. */
4-
stack<long double> s;
5-
long min;
64

5+
/*
6+
We do 2 * x - minEle to maintain a flag for pop operation
7+
So in pop operation when we encounter stack top < minEle; it is an indicator that this is the element where the minEle was updated.
8+
The flag basically acts as a medium to jump to the previous minElement when we pop the current minElement.
9+
10+
11+
(2 * currEle - minEle) ==> push
12+
(2 * minEle - currEle) ==> pop
13+
*/
14+
15+
16+
int minEle = 0;
17+
stack<int> s;
718
MinStack() {
819

920
}
1021

11-
void push(long double x) {
12-
if(s.empty()) { //if stack is empty just push and set it as min
13-
s.push(x);
14-
min = x;
15-
}
16-
else{
17-
if(x < min) { //if current value is less than current min, create flag in stack as 2 * x - min which will allow to traverse amongst next min while popping
18-
s.push(2 * x - min);
19-
min = x;
20-
}
21-
else
22-
s.push(x); //just push current x
22+
void push(int val) {
23+
if(s.empty()) {
24+
s.push(val);
25+
minEle = val;
2326
}
27+
28+
if(val < minEle) {
29+
s.push(2 * val - minEle);
30+
minEle = val;
31+
}
32+
33+
else s.push(val);
2434
}
2535

2636
void pop() {
27-
if(!s.empty()){ //if stack is non empty
28-
if(s.top() < min) { //if current top is less than min, this indicates that the top is flag. Which means that we update the min to next closest min and then pop the current top
29-
min = 2 * min - s.top();
30-
s.pop();
31-
}
32-
else { //else just pop
33-
s.pop();
34-
}
37+
int currEle = s.top();
38+
if(currEle < minEle) {
39+
minEle = 2 * minEle - currEle;
3540
}
41+
s.pop();
3642
}
3743

3844
int top() {
39-
if(s.top() < min) { //if top is less than min
40-
return min;
41-
}
45+
if(s.empty()) return -1;
46+
if(s.top() < minEle) return minEle;
4247
else return s.top();
4348
}
4449

4550
int getMin() {
46-
return min;
51+
if(s.empty()) return -1;
52+
return minEle;
4753
}
4854
};
4955

5056
/**
5157
* Your MinStack object will be instantiated and called as such:
5258
* MinStack* obj = new MinStack();
53-
* obj->push(x);
59+
* obj->push(val);
5460
* obj->pop();
5561
* int param_3 = obj->top();
5662
* int param_4 = obj->getMin();

0 commit comments

Comments
 (0)