Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Next_Greater_Element.cpp to cpp #172

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions cpp/Next_Greater_Element.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*Problem Statement - Given an array, print the Next Greater Element (NGE) for every element.
The Next greater Element for an element x is the first greater element on the right side of x in the array.
Elements for which no greater element exist, consider the next greater element as -1. */

//Problem Link - https://www.geeksforgeeks.org/next-greater-element/

#include<bits/stdc++.h>
using namespace std;
vector<int> nextLargerElement(vector<int> arr, int n)
{

vector<int> ans(n);
stack<int> st;
st.push(n-1);
ans[n-1]=-1;

for(int i=n-2; i>=0; i--)
{
if(st.empty())
{
ans[i] = -1;
st.push(i);
}
else
{
while(!st.empty() && arr[st.top()]<arr[i])
{
st.pop();
}
if(st.empty())
{
ans[i]=-1;
}
else
{
ans[i] = arr[st.top()];
}
st.push(i);
}
}
return ans;
}
int main()
{
int n;
cin>>n;

vector<int> arr(n);
for(int i=0; i<n; i++)
{
cin>>arr[i];
}

vector<int> ans = nextLargerElement(arr, n);
for(int i=0; i<n; i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
}