Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Number of NGEs to the right

  • Difficulty Level : Hard
  • Last Updated : 31 Aug, 2021

Given an array of n integers and q queries, print the number of next greater elements to the right of the given index element. 
Examples: 

Input: a[] = {3, 4, 2, 7, 5, 8, 10, 6}  
              q = 2 
              index = 0, 
              index = 5
Output: 6
        1 
Explanation:
The next greater elements
to the right of 3(index 0) are 4,7,5,8,10,6. 
The next greater elements to the right
of 8(index 5) are 10.

A naive approach is to iterate for every query from index to end, and find out the number of next greater elements to the right. This won’t be efficient enough as we run two nested loops 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Time Complexity: O(N) to answer a query. 
Auxiliary space: O(1) 



Better approach is to store the next greater index of every element and run a loop for every query that iterates from index and keeping the increasing counter as j = next[i]. This will avoid checking all elements and will directly jump to the next greater element of every element. But this won’t be efficient enough in cases like 1 2 3 4 5 6, where the next greater elements are sequentially increasing, ending it up in taking O(n) for every query.

Time complexity: O(N) to answer a query. 
Auxiliary space: O(N) for next greater element.

Efficient approach is to store the next greater elements index using next greater element in a next[] array. Then create a dp[] array that starts from n-2, as n-1th index will have no elements to its right and dp[n-1] = 0. While traversing from back we use dynamic programming to count the number of elements to the right where we use memoization as dp[next[i]] which gives us a count of the numbers to the right of the next greater element of the current element, hence we add 1 to it. If next[i]=-1 then we do not have any element to the right hence dp[i]=0. dp[index] stores the count of the number of next greater elements to the right.

Below is the implementation of the above approach. 

C++




#include <bits/stdc++.h>
using namespace std;
 
// array to store the next greater element index
void fillNext(int next[], int a[], int n)
{
    // use of stl stack in c++
    stack<int> s;
 
    // push the 0th index to the stack
    s.push(0);
 
    // traverse in the loop from 1-nth index
    for (int i = 1; i < n; i++) {
 
        // iterate till loop is empty
        while (!s.empty()) {
 
            // get the topmost index in the stack
            int cur = s.top();
 
            // if the current element is greater
            // then the top index-th element, then
            // this will be the next greatest index
            // of the top index-th element
            if (a[cur] < a[i]) {
 
                // initialize the cur index position's
                // next greatest as index
                next[cur] = i;
 
                // pop the cur index as its greater
                // element has been found
                s.pop();
            }
 
            // if not greater then break
            else
                break;
        }
 
        // push the i index so that its next greatest
        // can be found
        s.push(i);
    }
 
    // iterate for all other index left inside stack
    while (!s.empty()) {
 
        int cur = s.top();
 
        // mark it as -1 as no element in greater
        // then it in right
        next[cur] = -1;
 
        s.pop();
    }
}
 
// Function to count the number of
// next greater numbers to the right
void count(int a[], int dp[], int n)
{
    // initializes the next array as 0
    int next[n];
    memset(next, 0, sizeof(next));
 
    // calls the function to pre-calculate
    // the next greatest element indexes
    fillNext(next, a, n);
 
    for (int i = n - 2; i >= 0; i--) {
 
        // if the i-th element has no next
        // greater element to right
        if (next[i] == -1)
            dp[i] = 0;
 
        // Count of next greater numbers to right.
        else
            dp[i] = 1 + dp[next[i]];
    }
}
 
// answers all queries in O(1)
int answerQuery(int dp[], int index)
{
    // returns the number of next greater
    // elements to the right.
    return dp[index];
}
 
// driver program to test the above function
int main()
{
    int a[] = { 3, 4, 2, 7, 5, 8, 10, 6 };
    int n = sizeof(a) / sizeof(a[0]);
 
    int dp[n];
 
    // calls the function to count the number
    // of greater elements to the right for
    // every element.
    count(a, dp, n);
 
    // query 1 answered
    cout << answerQuery(dp, 3) << endl;
 
    // query 2 answered
    cout << answerQuery(dp, 6) << endl;
 
    // query 3 answered
    cout << answerQuery(dp, 1) << endl;
 
    return 0;
}

Java




// Java program to print number of NGEs to the right
import java.util.*;
 
class GFG
{
 
// array to store the next greater element index
static void fillNext(int next[], int a[], int n)
{
    // Use stack
    Stack<Integer> s = new Stack<Integer>();
 
    // push the 0th index to the stack
    s.push(0);
 
    // traverse in the loop from 1-nth index
    for (int i = 1; i < n; i++)
    {
 
        // iterate till loop is empty
        while (s.size() > 0)
        {
 
            // get the topmost index in the stack
            int cur = s.peek();
 
            // if the current element is greater
            // then the top index-th element, then
            // this will be the next greatest index
            // of the top index-th element
            if (a[cur] < a[i])
            {
 
                // initialize the cur index position's
                // next greatest as index
                next[cur] = i;
 
                // pop the cur index as its greater
                // element has been found
                s.pop();
            }
 
            // if not greater then break
            else
                break;
        }
 
        // push the i index so that its next greatest
        // can be found
        s.push(i);
    }
 
    // iterate for all other index left inside stack
    while (s.size() > 0)
    {
 
        int cur = s.peek();
 
        // mark it as -1 as no element in greater
        // then it in right
        next[cur] = -1;
 
        s.pop();
    }
}
 
// function to count the number of
// next greater numbers to the right
static void count(int a[], int dp[], int n)
{
    // initializes the next array as 0
    int next[] = new int[n];
    for(int i = 0; i < n; i++)
    next[i] = 0;
     
    // calls the function to pre-calculate
    // the next greatest element indexes
    fillNext(next, a, n);
 
    for (int i = n - 2; i >= 0; i--)
    {
 
        // if the i-th element has no next
        // greater element to right
        if (next[i] == -1)
            dp[i] = 0;
 
        // Count of next greater numbers to right.
        else
            dp[i] = 1 + dp[next[i]];
    }
}
 
// answers all queries in O(1)
static int answerQuery(int dp[], int index)
{
    // returns the number of next greater
    // elements to the right.
    return dp[index];
}
 
// driver code
public static void main(String args[])
{
    int a[] = { 3, 4, 2, 7, 5, 8, 10, 6 };
    int n = a.length;
 
    int dp[] = new int[n];
 
    // calls the function to count the number
    // of greater elements to the right for
    // every element.
    count(a, dp, n);
 
    // query 1 answered
    System.out.println(answerQuery(dp, 3));
 
    // query 2 answered
    System.out.println( answerQuery(dp, 6));
     
    // query 3 answered
    System.out.println( answerQuery(dp, 1) );
 
}
}
 
// This code is contributed by Arnab Kundu

Python3




# Python3 program to print number of NGEs to the right
 
# array to store the next greater element index
def fillNext(Next, a, n):
    # Use stack
    s = []
  
    # push the 0th index to the stack
    s.append(0)
  
    # traverse in the loop from 1-nth index
    for i in range(1, n):
       
        # iterate till loop is empty
        while (len(s) > 0):
           
            # get the topmost index in the stack
            cur = s[-1]
             
            # if the current element is greater
            # then the top index-th element, then
            # this will be the next greatest index
            # of the top index-th element
            if (a[cur] < a[i]):
               
                # initialize the cur index position's
                # next greatest as index
                Next[cur] = i
                 
                # pop the cur index as its greater
                # element has been found
                s.pop()
  
            # if not greater then break
            else:
                break
  
        # push the i index so that its next greatest
        # can be found
        s.append(i)
  
    # iterate for all other index left inside stack
    while (len(s) > 0):
        cur = s[-1]
        # mark it as -1 as no element in greater
        # then it in right
        Next[cur] = -1
        s.pop()
  
# function to count the number of
# next greater numbers to the right
def count(a, dp, n):
    # initializes the next array as 0
    Next = [0]*(n)
    for i in range(n):
        Next[i] = 0
    # calls the function to pre-calculate
    # the next greatest element indexes
    fillNext(Next, a, n)
  
    for i in range(n - 2, -1, -1):
        # if the i-th element has no next
        # greater element to right
        if (Next[i] == -1):
            dp[i] = 0
  
        # Count of next greater numbers to right.
        else:
            dp[i] = 1 + dp[Next[i]]
  
# answers all queries in O(1)
def answerQuery(dp, index):
    # returns the number of next greater
    # elements to the right.
    return dp[index]
 
a = [ 3, 4, 2, 7, 5, 8, 10, 6 ]
n = len(a)
 
dp = [0]*(n)
 
# calls the function to count the number
# of greater elements to the right for
# every element.
count(a, dp, n)
 
# query 1 answered
print(answerQuery(dp, 3))
 
# query 2 answered
print(answerQuery(dp, 6))
  
# query 3 answered
print(answerQuery(dp, 1))
 
# This code is contributed by divyesh072019.

C#




// C# program to print number of
// NGEs to the right
using System;
using System.Collections;
 
class GFG
{
 
// array to store the next greater element index
static void fillNext(int []next, int []a, int n)
{
    // Use stack
    Stack s = new Stack();
 
    // Push the 0th index to the stack
    s.Push(0);
 
    // traverse in the loop from 1-nth index
    for (int i = 1; i < n; i++)
    {
 
        // iterate till loop is empty
        while (s.Count > 0)
        {
 
            // get the topmost index in the stack
            int cur = (int)s.Peek();
 
            // if the current element is greater
            // then the top index-th element, then
            // this will be the next greatest index
            // of the top index-th element
            if (a[cur] < a[i])
            {
 
                // initialize the cur index position's
                // next greatest as index
                next[cur] = i;
 
                // Pop the cur index as its greater
                // element has been found
                s.Pop();
            }
 
            // if not greater then break
            else
                break;
        }
 
        // Push the i index so that its next
        // greatest can be found
        s.Push(i);
    }
 
    // iterate for all other index
    // left inside stack
    while (s.Count > 0)
    {
 
        int cur =(int) s.Peek();
 
        // mark it as -1 as no element in
        // greater then it in right
        next[cur] = -1;
 
        s.Pop();
    }
}
 
// function to count the number of
// next greater numbers to the right
static void count(int []a, int []dp, int n)
{
    // initializes the next array as 0
    int []next = new int[n];
    for(int i = 0; i < n; i++)
        next[i] = 0;
     
    // calls the function to pre-calculate
    // the next greatest element indexes
    fillNext(next, a, n);
 
    for (int i = n - 2; i >= 0; i--)
    {
 
        // if the i-th element has no next
        // greater element to right
        if (next[i] == -1)
            dp[i] = 0;
 
        // Count of next greater numbers to right.
        else
            dp[i] = 1 + dp[next[i]];
    }
}
 
// answers all queries in O(1)
static int answerQuery(int []dp, int index)
{
    // returns the number of next greater
    // elements to the right.
    return dp[index];
}
 
// Driver code
public static void Main(String []args)
{
    int []a = { 3, 4, 2, 7, 5, 8, 10, 6 };
    int n = a.Length;
 
    int []dp = new int[n];
 
    // calls the function to count the number
    // of greater elements to the right for
    // every element.
    count(a, dp, n);
 
    // query 1 answered
    Console.WriteLine(answerQuery(dp, 3));
 
    // query 2 answered
    Console.WriteLine( answerQuery(dp, 6));
     
    // query 3 answered
    Console.WriteLine( answerQuery(dp, 1));
}
}
 
// This code is contributed by Arnab Kundu

Javascript




<script>
// Javascript program to print number of NGEs to the right
 
// array to store the next greater element index
function fillNext(next,a,n)
{
    // Use stack
    let s = [];
  
    // push the 0th index to the stack
    s.push(0);
  
    // traverse in the loop from 1-nth index
    for (let i = 1; i < n; i++)
    {
  
        // iterate till loop is empty
        while (s.length > 0)
        {
  
            // get the topmost index in the stack
            let cur = s[s.length-1];
  
            // if the current element is greater
            // then the top index-th element, then
            // this will be the next greatest index
            // of the top index-th element
            if (a[cur] < a[i])
            {
  
                // initialize the cur index position's
                // next greatest as index
                next[cur] = i;
  
                // pop the cur index as its greater
                // element has been found
                s.pop();
            }
  
            // if not greater then break
            else
                break;
        }
  
        // push the i index so that its next greatest
        // can be found
        s.push(i);
    }
  
    // iterate for all other index left inside stack
    while (s.length > 0)
    {
  
        let cur = s[s.length-1];
  
        // mark it as -1 as no element in greater
        // then it in right
        next[cur] = -1;
  
        s.pop();
    }
}
 
// function to count the number of
// next greater numbers to the right
function count(a,dp,n)
{
    // initializes the next array as 0
    let next = new Array(n);
    for(let i = 0; i < n; i++)
        next[i] = 0;
      
    // calls the function to pre-calculate
    // the next greatest element indexes
    fillNext(next, a, n);
  
    for (let i = n - 2; i >= 0; i--)
    {
  
        // if the i-th element has no next
        // greater element to right
        if (next[i] == -1)
            dp[i] = 0;
  
        // Count of next greater numbers to right.
        else
            dp[i] = 1 + dp[next[i]];
    }
}
 
// answers all queries in O(1)
function answerQuery(dp,index)
{
    // returns the number of next greater
    // elements to the right.
    return dp[index];
}
 
// driver code
let a=[3, 4, 2, 7, 5, 8, 10, 6 ];
let n = a.length;
let dp=new Array(n);
 
// calls the function to count the number
// of greater elements to the right for
// every element.
count(a, dp, n);
 
// query 1 answered
document.write(answerQuery(dp, 3)+"<br>");
 
// query 2 answered
document.write( answerQuery(dp, 6)+"<br>");
 
// query 3 answered
document.write( answerQuery(dp, 1) +"<br>");
 
// This code is contributed by avanitrachhadiya2155
</script>
Output
2
0
3

Time complexity: O(1) to answer a query. 
Auxiliary Space: O(n) 
Alternate Shorter Implementation
 

C++




#include <bits/stdc++.h>
using namespace std;
 
vector<int> no_NGN(int arr[], int n)
{
    vector<int> nxt;
 
    // use of stl stack in c++
    stack<int> s;
 
    nxt.push_back(0);
    // push the (n-1)th index to the stack
    s.push(n - 1);
 
    // traverse in reverse order
    for (int i = n - 2; i >= 0; i--) {
        while (!s.empty() && arr[i] >= arr[s.top()])
            s.pop();
 
         
        // if no element is greater than arr[i] the
        // number of NGEs to right is 0
        if (s.empty())
            nxt.push_back(0);
         
        else
         
            // number of NGEs to right of arr[i] is
            // one greater than the number of NGEs to right
            // of higher number to its right
            nxt.push_back(nxt[n - s.top() - 1] + 1);
         
        s.push(i);
    }
 
    // reverse again because values are in reverse order
    reverse(nxt.begin(), nxt.end());
 
    // returns the vector of number of next
    // greater elements to the right of each index.
    return nxt;
}
 
int main()
{
    int n = 8;
 
    int arr[] = { 3, 4, 2, 7, 5, 8, 10, 6 };
 
    vector<int> nxt = no_NGN(arr, n);
 
    // query 1 answered
    cout << nxt[3] << endl;
 
    // query 2 answered
    cout << nxt[6] << endl;
 
    // query 3 answered
    cout << nxt[1] << endl;
 
    return 0;
}

Java




import java.util.*;
class GFG{
 
static Vector<Integer> no_NGN(int arr[], int n)
{
    Vector<Integer> nxt = new Vector<>();
 
    // use of stl stack in Java
    Stack<Integer> s = new Stack<>();
    nxt.add(0);
   
    // push the (n-1)th index to the stack
    s.add(n - 1);
 
    // traverse in reverse order
    for (int i = n - 2; i >= 0; i--)
    {
        while (!s.isEmpty() && arr[i] >= arr[s.peek()])
            s.pop();
 
         
        // if no element is greater than arr[i] the
        // number of NGEs to right is 0
        if (s.isEmpty())
            nxt.add(0);
         
        else
         
            // number of NGEs to right of arr[i] is
            // one greater than the number of NGEs to right
            // of higher number to its right
            nxt.add(nxt.get(n - s.peek() - 1 ) + 1);
         
        s.add(i);
    }
 
    // reverse again because values are in reverse order
    Collections.reverse(nxt);
 
    // returns the vector of number of next
    // greater elements to the right of each index.
    return nxt;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 8;
    int arr[] = { 3, 4, 2, 7, 5, 8, 10, 6 };
    Vector<Integer> nxt = no_NGN(arr, n);
   
    // query 1 answered
    System.out.print(nxt.get(3) +"\n");
 
    // query 2 answered
    System.out.print(nxt.get(6) +"\n");
 
    // query 3 answered
    System.out.print(nxt.get(1) +"\n");
}
}
 
// This code is contributed by Rajput-Ji

Python3




def no_NGN(arr, n):
    nxt = []
  
    # use of stl stack in Java
    s = []
    nxt.append(0);
    
    # push the (n-1)th index to the stack
    s.append(n - 1)
  
    # traverse in reverse order
    for i in range(n - 2, -1, -1):
        while len(s)!=0 and arr[i] >= arr[s[-1]]:
            s.pop()
          
        # if no element is greater than arr[i] the
        # number of NGEs to right is 0
        if len(s) == 0:
            nxt.append(0)
        else:
            # number of NGEs to right of arr[i] is
            # one greater than the number of NGEs to right
            # of higher number to its right
            nxt.append(nxt[n - s[-1] - 1 ] + 1)
          
        s.append(i)
  
    # reverse again because values are in reverse order
    nxt.reverse()
  
    # returns the vector of number of next
    # greater elements to the right of each index.
    return nxt
 
n = 8
arr = [ 3, 4, 2, 7, 5, 8, 10, 6 ]
nxt = no_NGN(arr, n)
 
# query 1 answered
print(nxt[3])
 
# query 2 answered
print(nxt[6])
 
# query 3 answered
print(nxt[1])
 
# This code is contributed by suresh07.

C#




using System;
using System.Collections.Generic;
public class GFG{
static List<int> no_NGN(int []arr, int n)
{
    List<int> nxt = new List<int>();
 
    // use of stl stack in Java
    Stack<int> s = new Stack<int>();
    nxt.Add(0);
   
    // push the (n-1)th index to the stack
    s.Push(n - 1);
 
    // traverse in reverse order
    for (int i = n - 2; i >= 0; i--)
    {
        while (s.Count!=0 && arr[i] >= arr[s.Peek()])
            s.Pop();
 
         
        // if no element is greater than arr[i] the
        // number of NGEs to right is 0
        if (s.Count == 0)
            nxt.Add(0);
         
        else
         
            // number of NGEs to right of arr[i] is
            // one greater than the number of NGEs to right
            // of higher number to its right
            nxt.Add(nxt[n - s.Peek() - 1 ] + 1);
         
        s.Push(i);
    }
 
    // reverse again because values are in reverse order
    nxt.Reverse();
 
    // returns the vector of number of next
    // greater elements to the right of each index.
    return nxt;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 8;
    int []arr = { 3, 4, 2, 7, 5, 8, 10, 6 };
    List<int> nxt = no_NGN(arr, n);
   
    // query 1 answered
    Console.Write(nxt[3] +"\n");
 
    // query 2 answered
    Console.Write(nxt[6] +"\n");
 
    // query 3 answered
    Console.Write(nxt[1] +"\n");
}
}
 
// This code iscontributed by aashish1995

Javascript




<script>
 
 
function no_NGN(arr, n)
{
    var nxt = [];
 
    // use of stl stack in c++
    var s = [];
 
    nxt.push(0);
    // push the (n-1)th index to the stack
    s.push(n - 1);
 
    // traverse in reverse order
    for (var i = n - 2; i >= 0; i--) {
        while (s.length!=0 && arr[i] >= arr[s[s.length-1]])
            s.pop();
 
         
        // if no element is greater than arr[i] the
        // number of NGEs to right is 0
        if (s.length==0)
            nxt.push(0);
         
        else
         
            // number of NGEs to right of arr[i] is
            // one greater than the number of NGEs to right
            // of higher number to its right
            nxt.push(nxt[n - s[s.length-1] - 1] + 1);
         
        s.push(i);
    }
 
    // reverse again because values are in reverse order
    nxt.reverse();
 
    // returns the vector of number of next
    // greater elements to the right of each index.
    return nxt;
}
 
var n = 8;
var arr = [3, 4, 2, 7, 5, 8, 10, 6];
var nxt = no_NGN(arr, n);
// query 1 answered
document.write( nxt[3] + "<br>");
// query 2 answered
document.write( nxt[6]  + "<br>");
// query 3 answered
document.write( nxt[1]  + "<br>");
 
</script>
Output
2
0
3

This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!