Next Greater Element - Popular DSA Questions

Next Greater Element - Popular DSA Questions

Next Greater Element

https://www.codingninjas.com/studio/problems/next-greater-element_670312

Hint Video:

Code:

#include<stack>
vector<int> nextGreaterElement(vector<int>& arr, int n)
{
    // Write your code here
    vector<int> nge(n,-1);
    stack<int> st;

    for(int i=n-1;i>=0;i--){
        while(!st.empty() && arr[i]>=st.top()){
            st.pop();
        }

        if(st.empty()){
            nge[i] = -1;
        }else{
            nge[i] = st.top();
        }
        st.push(arr[i]);
    }

    return nge;
}