-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmin_stack_extra_space.cpp
98 lines (71 loc) · 2.12 KB
/
min_stack_extra_space.cpp
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
/*
Design a data-structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. Your task is to complete all the functions, using stack data-Structure.
Input Format:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The first line of input contains an integer n denoting the number of integers in a sequence. In the second line are n space separated integers of the stack.
Output Format:
For each testcase, in a new line, print the minimum integer from the stack.
Your Task:
Since this is a function problem, you don't need to take inputs. You just have to complete 5 functions, push() which takes an integer x as input and pushes it into the stack; pop() which pops out the topmost element from the stack; isEmpty() which returns true/false depending upon whether the stack is empty or not; isFull() which takes the size of the stack as input and returns true/false depending upon whether the stack is full or not (depending upon the given size); getMin() which returns the minimum element of the stack.
Expected Time Complexity: O(1) for all the 5 functions.
Expected Auxiliary Space: O(1) for all the 5 functions.
Constraints:
1 <= T <= 100
1 <= N <= 100
Example:
Input:
1
5
18 19 29 15 16
Output:
15
*/
#include<iostream>
#include<stack>
using namespace std;
void push(int a);
bool isFull(int n);
bool isEmpty();
int pop();
int getMin();
stack<int> s;
int main(){
int t;
cin>>t;
while(t--){
int n,a;
cin>>n;
while(!isEmpty()){
pop();
}
while(!isFull(n)){
cin>>a;
push(a);
}
cout<<getMin()<<endl;
}
}
stack<int>ss;
void push(int a)
{
s.push(a);
if(ss.empty() || ss.top() >= a) ss.push(a);
}
bool isFull(int n)
{
if(s.size()==n) return true;
else return false;
}
bool isEmpty()
{
return s.empty();
}
int pop()
{ if(s.empty()) return -1;
if(s.top()==ss.top()) ss.pop();
s.pop();
}
int getMin()
{
if(!s.empty()) return ss.top();
else return -1;
}