-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpecial Stack (GFG) - GetMin in O(1) time and O(1) space
110 lines (103 loc) · 1.88 KB
/
Special Stack (GFG) - GetMin in O(1) time and O(1) space
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// GetMin in O(1) time and O(n) space
stack<int> s1;
void push(stack<int>& s, int a){
// Your code goes here
if(isEmpty(s)) {
s1.push(a);
}
else {
s1.push(min(a, s1.top()));
}
s.push(a);
}
bool isFull(stack<int>& s,int n){
// Your code goes here
return s.size() == n;
}
bool isEmpty(stack<int>& s){
// Your code goes here
return s.size() == 0;
}
int pop(stack<int>& s){
// Your code goes here
int x = s.top();
s.pop();
s1.pop();
return x;
}
int getMin(stack<int>& s){
// Your code goes here
return s1.top();
}
//------------------------------------------------------------------
// GetMin in O(n) time and O(1) space
void push(stack<int>& s, int a){
// Your code goes here
s.push(a);
}
bool isFull(stack<int>& s,int n){
// Your code goes here
return s.size() == n;
}
bool isEmpty(stack<int>& s){
// Your code goes here
return s.empty();
}
int pop(stack<int>& s){
// Your code goes here
int n = s.top();
s.pop();
return n;
}
void minimum(stack<int> &s, int &mn) {
if(s.size() == 0) return;
int x = s.top();
s.pop();
mn = min(mn, x);
minimum(s, mn);
s.push(x);
}
int getMin(stack<int>& s){
// Your code goes here
int ans = 1e9;
minimum(s, ans);
return ans;
}
//----------------------------------------------------
// GetMin in O(1) time and O(1) space
int Min = 1e9;
void push(stack<int>& s, int a){
// Your code goes here
if(s.empty()) {
Min = 1e9;
s.push(a);
}
else if(a >= Min)
s.push(a);
else
s.push(a - (Min - a));
Min = min(Min, a);
}
bool isFull(stack<int>& s,int n){
// Your code goes here
return s.size() == n;
}
bool isEmpty(stack<int>& s){
// Your code goes here
return s.size() == 0;
}
int pop(stack<int>& s){
// Your code goes here
int x = s.top();
s.pop();
if(x < Min) {
int temp = Min;
Min = 2 * Min - x;
x = temp;
}
return x;
}
int getMin(stack<int>& s){
// Your code goes here
return Min;
}