Next Greater Element Using Stack in O(n) time. GFG

Statement - Given an array arr[ ] of size N having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array.

Next greater element of an element in the array is the nearest element on the right which is greater than the current element.
If there does not exist next greater of current element, then next greater element for current element is -1. For example, next greater of the last element is always -1.

Test Case - 

Input: 
N = 4, arr[] = [1 3 2 4]
Output:
3 4 4 -1
Explanation:
In the array, the next larger element 
to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? 
since it doesn't exist, it is -1.

Problem Link - Click

Code - Solved Using Stack, Time Complexity O(n) and Space Complexity O(n).

Don't be in doubt that there is a while loop under for loop so time complexity should be O(n ^ 2). (X wrong)

Because, in stack we will put any element at once in a hole for loop iteration, think about it you will get easily.

#define ll long long int

#define pb push_back

vector<long long> nextLargerElement(vector<long long> arr, int n){

    // Your code here    

    if(n == 1) return {-1};

    vector<ll> ans;

    ans.pb(-1);

    stack<ll> st;

    st.push(arr[n-1]);

   for(int i = n - 2; i >= 0; i--)

   {       

       bool check = true;

 // we will put any element in the stack only 1 times so it has constant time complexity O(1) for 1 iteration.

       while(!st.empty())

       {

           if(st.top() > arr[i])

           {

               ans.pb(st.top());

               check = false;

               break;

           }

           else

           {

               st.pop();

           }

       }

       if(check)

       ans.pb(-1);  

       st.push(arr[i]);

   }

   reverse(ans.begin(), ans.end());

   return ans;

}

Special Discount For You




Reactions

Post a Comment

0 Comments