Next Greater Element | Practice | GeeksforGeeks

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.
Example 1:
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.

Example 2:
Input: 
N = 5, arr[] [6 8 0 1 3]
Output:
8 -1 1 3 -1
Explanation:
In the array, the next larger element to 
6 is 8, for 8 there is no larger elements 
hence it is -1, for 0 it is 1 , for 1 it 
is 3 and then for 3 there is no larger 
element on right and hence -1.
Your Task:
This is a function problem. You only need to complete the function nextLargerElement() that takes list of integers arr[ ] and N as input parameters and returns list of integers of length N denoting the next greater elements for all the corresponding elements in the input array.
Expected Time Complexity : O(N)
Expected Auxiliary Space : O(N)
Constraints:
1 ≤ N ≤ 106
1 ≤ Ai ≤ 1018
+1
bhadoriyashiva7354in 7 hours
class Solution:
    def nextLargerElement(self,arr,n):
        #code here
        stack, lst = [], []
        
        for i in range(n-1, -1, -1):
            if len(stack) == 0:
                lst.append(-1)
            elif (len(stack) > 0 and stack[-1] > arr[i]):
                lst.append(stack[-1])
            elif (len(stack) > 0 and stack[-1] <= arr[i]):
                while (len(stack) > 0 and stack[-1] <= arr[i]):
                    stack.pop()
                if len(stack) == 0:
                    lst.append(-1)
                else:
                    lst.append(stack[-1])
            stack.append(arr[i])
        return lst[::-1]
+1
putyavka6 days ago
vector<long long> nextLargerElement(vector<long long> arr, int n){
    vector<long long> res(n);
    stack<long long> S;
    for (int i = n - 1; i >= 0; i--) {
        while (S.size() && S.top() < arr[i])
            S.pop();
        res[i] = S.size() ? S.top() : -1;
        S.push(arr[i]);
    }
    return res;
}

0
cse19bcs60561 week ago
JAVA SOLUTION
   public static long[] nextLargerElement(long[] arr, int n)   {        long ans[]=new long[n];       Stack<Long> st= new Stack<Long>();              for(int i=arr.length-1;i>=0;i--)       {                   while(st.size()!=0&&st.peek()<=arr[i])                   {                       st.pop();                                     }                   if(st.size()==0)                   ans[i]=(long)-1;                                      else                   {                      ans[i]=st.peek();                   }                          st.push(arr[i]);       }       return ans;   }  
0
garjeaniket71 week ago
  // Your code here       Stack<Long>st = new Stack<>();       int i =n-1;       while(i>=0){           if(st.empty()){               st.push(arr[i]);               arr[i]=-1;               i--;           }           else{               if(st.peek()>arr[i]){                   long temp=arr[i];                   arr[i]=st.peek();                   st.push(temp);                   i--;               }               else{                                      st.pop();               }           }       }       return arr;
+1
19bcs13141 week ago
O(n) Solution using stack
 
class Solution
{
    //Function to find the next greater element for each element of the array.
    public static long[] nextLargerElement(long[] arr, int n)
    { 
        // Your code here
        long[] ans=new long[n];
        Stack<Long> s=new Stack<>();
        
        
        for(int i=n-1;i>=0;i--){
            if(s.size()==0){
                s.push((long)-1);
                ans[i]=s.peek();
            }else if(s.size()!=0 && s.peek()> arr[i]){
                ans[i]=s.peek();
            }else if(s.size()!=0 && s.peek()<=arr[i]){
                while(s.size()!=0 && s.peek()<=arr[i]) s.pop();
                
                if(s.size()==0){
                    ans[i]=(long)-1;
                    s.push((long)-1);
                }else{
                    ans[i]=s.peek();
                }
            }
            
            s.push(arr[i]);
        }
        return ans ;
    } 
}
-1
nevilvas2 weeks ago
class Solution:
    def nextLargerElement(self,arr,n):
        #code here
        s = []
        ans = []
        for i in range(n-1,-1,-1):
            while len(s) != 0 and arr[i] > s[-1]: 
                s.pop()
                
            if len(s) == 0:
                ans.append(-1)
            else:
                ans.append(s[-1])
            
            s.append(arr[i])
        
                
                
                
        ans = ans[::-1]   
        return ans
0
jotarokujo2 weeks ago
// pattern: wall-hit
public static long[] nextLargerElement(long[] arr, int n) {
       Stack<Long> stack = new Stack<Long>();
       long[] ans = new long[n + 1];
       for (int i = n - 1; i >= 0; i -= 1) {
           while (!stack.isEmpty()
           			&& stack.peek() <= arr[i]) {
               stack.pop();
           }
           if (stack.isEmpty()) {
               ans[i] = -1;
           } else {
               ans[i] = stack.peek();
           }
           stack.push(arr[i]);
       }
       return ans;
   }
-1
manish14092 weeks ago
very short code and easy in c++
vector<long long> nextLargerElement(vector<long long> arr, int n){       // manish kumar       stack<long long>st;       st.push(-1);       vector<long long>ans(n,0);       for(int i=n-1;i>=0;i--){           while(st.top()!=-1 and arr[i]>=st.top())st.pop();           ans[i]=st.top();           st.push(arr[i]);       }       return ans;   }
0
abhinavbisht0252 weeks ago
using C++
vector<long long> nextLargerElement(vector<long long> arr, int n){
        // Your code here
        vector<long long> result;
        stack<long long> st;
        
        for(int i = n-1; i>=0; i--)
        {
            if(st.size() == 0)
            {
                result.push_back(-1);
            }
            else if(st.size() > 0 && st.top() > arr[i])
            {
                result.push_back(st.top());
            }
            else if(st.size() > 0 && st.top() <= arr[i])
            {
                while(st.size() > 0 && st.top() <= arr[i])
                {
                    st.pop();
                }
                if(st.size() == 0)
                {
                    result.push_back(-1);
                }
                else{
                    result.push_back(st.top());
                }
            }
            st.push(arr[i]);
        }
        reverse(result.begin(),result.end());
        return result;
    }
0
hharshit81182 weeks ago
void StackQueue :: push(int x){   s1.push(x);}
//Function to pop an element from queue by using 2 stacks.int StackQueue :: pop(){   if(s1.empty() == false){       while(s1.size() != 1){           s2.push(s1.top());           s1.pop();       }       int x = s1.top();       s1.pop();       while(s2.empty() == false){           s1.push(s2.top());           s2.pop();       }       return x;   }   else{       return -1;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.