Skip to content

Commit f9be9ae

Browse files
Added solution to min_stack
1 parent 6d8c7e2 commit f9be9ae

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

min_stack_o(1).cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class MinStack {
2+
public:
3+
/** initialize your data structure here. */
4+
stack<long double> s;
5+
long min;
6+
7+
MinStack() {
8+
9+
}
10+
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
23+
}
24+
}
25+
26+
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+
}
35+
}
36+
}
37+
38+
int top() {
39+
if(s.top() < min) { //if top is less than min
40+
return min;
41+
}
42+
else return s.top();
43+
}
44+
45+
int getMin() {
46+
return min;
47+
}
48+
};
49+
50+
/**
51+
* Your MinStack object will be instantiated and called as such:
52+
* MinStack* obj = new MinStack();
53+
* obj->push(x);
54+
* obj->pop();
55+
* int param_3 = obj->top();
56+
* int param_4 = obj->getMin();
57+
*/

0 commit comments

Comments
 (0)