-
Notifications
You must be signed in to change notification settings - Fork 5
/
NextSmallerElement.cpp
41 lines (38 loc) · 968 Bytes
/
NextSmallerElement.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
#include <bits/stdc++.h>
using namespace std;
//Time Complexity O(n)
vector<long long> nextSmallerElement(vector<long long> arr, int n){
vector<long long int>v;
stack<long long int>s;
for(int i=n-1;i>=0;i--)
{
if(s.size()==0)
v.push_back(-1);
else if(s.size()>0 && s.top()<arr[i])
v.push_back(s.top());
else
{
while(s.size()>0 && s.top()>arr[i])
s.pop();
if(s.size()==0)
v.push_back(-1);
else
v.push_back(s.top());
}
s.push(arr[i]);
}
reverse(v.begin(),v.end());
return v;
}
int main()
{
int n;
cin>>n;
vector<long long int>a(n),res;
for(int i=0;i<n;i++)
cin>>a[i];
res=nextSmallerElement(a,n);
for(int i=0;i<n;i++)
cout<<res[i]<<" ";
return 0;
}