Skip to content

Commit

Permalink
Stack and Queues
Browse files Browse the repository at this point in the history
Find the next Greater element
  • Loading branch information
dhruviagrawal committed Mar 28, 2021
1 parent 42e395e commit 62323a0
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions NextGreaterElement.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <bits/stdc++.h>
using namespace std;
//Time Complexity O(n)
vector<long long> nextLargerElement(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=nextLargerElement(a,n);
for(int i=0;i<n;i++)
cout<<res[i]<<" ";
return 0;
}

0 comments on commit 62323a0

Please sign in to comment.