You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: min_stack_o(1).cpp
+33-27Lines changed: 33 additions & 27 deletions
Original file line number
Diff line number
Diff line change
@@ -1,56 +1,62 @@
1
1
classMinStack {
2
2
public:
3
3
/** initialize your data structure here. */
4
-
stack<longdouble> s;
5
-
long min;
6
4
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;
7
18
MinStack() {
8
19
9
20
}
10
21
11
-
voidpush(longdouble 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
+
voidpush(int val) {
23
+
if(s.empty()) {
24
+
s.push(val);
25
+
minEle = val;
23
26
}
27
+
28
+
if(val < minEle) {
29
+
s.push(2 * val - minEle);
30
+
minEle = val;
31
+
}
32
+
33
+
else s.push(val);
24
34
}
25
35
26
36
voidpop() {
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;
35
40
}
41
+
s.pop();
36
42
}
37
43
38
44
inttop() {
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;
42
47
elsereturn s.top();
43
48
}
44
49
45
50
intgetMin() {
46
-
return min;
51
+
if(s.empty()) return -1;
52
+
return minEle;
47
53
}
48
54
};
49
55
50
56
/**
51
57
* Your MinStack object will be instantiated and called as such:
0 commit comments