forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smallest_element_in_an_array.cpp
167 lines (124 loc) · 3.14 KB
/
smallest_element_in_an_array.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/* Program to find the minimum element of an array using stack in O(1) space complexity and time complexity.
Given Array A[]={1,2,-1,4,5};
Then we will first create a stack of array of elemnents by pushing array elements and then find minimum
of them:-
We define a variable min that stores the current minimum element in the stack.To handle the case when minimum element is removed
we push “2x – minEle” into the stack instead of x so that previous minimum element can be retrieved using current min and its value stored in stack.
*/
#include <bits/stdc++.h>
using namespace std;
//Creating a user-defined structure for operation on stack;
class UserStack
{
private:
stack<int> s;
int min;
public:
int getMin()
{
if (s.empty())
{
//Invalid operation hence returning INT_MAX;
return INT_MAX;
}
else
{
return min;
}
}
void push(int x)
{
if (s.empty())
{
min = x;
s.push(x);
return;
}
// If new number to be pushed is less than min
if (x < min)
{
s.push(2*x - min);
min = x;
}
else
{
s.push(x);
}
}
void peek()
{
if (s.empty())
{
cout << "Stack is empty ";
return;
}
int t = s.top();
// If t < min means min stores value of t.
cout << "Top Most Element is:";
if(t<min)
{
cout<<min<<"\n";
}
else
{
cout<<t<<"\n";
}
}
void pop()
{
if (s.empty())
{
cout << "Stack is empty can't do pop operation\n";
return;
}
int t = s.top();
s.pop();
/* Minimum will change as the minimum element
of the stack is being removed. */
if (t < min)
{
min = 2*min - t;
}
}
};
int main()
{
int size;
cout<<"Enter the size of array of which you want to find minimum\n";
cin>>size;
int A[size];
cout<<"Enter the elements of array\n";
for(int i=0;i<size;i++)
{
cin>>A[i];
}
//Creating an object of UserStack class defined by us
UserStack S;
for(int i=0;i<size;i++)
{
S.push(A[i]);
}
if(S.getMin()==INT_MAX)
{
cout<<"Stack is empty\n";
}
else
{
cout<<"The minimum element of the array using stack is:"<<S.getMin()<<"\n";
}
return 0;
}
/*
//Complexity Analysis
Time Complexity:-O(1) in finding minimum element (getMin() operation)
O(1) for pushing and popping operation.
O(N) for pushing array elements in stack.
Space Complexity:-O(1)
//Input-Output Format
Input:- 5
1,2,-2,7,6
Output:- -2
Input:- 9
-1,-2,-9,7,6,11,34,9,8
Output:- -9
*/