Given an array of integers, find the next greater element for every element in the array. The next greater element of a number x is the first greater number to the right of x in the array.

In other words, for each element A[i] in the array, find an element A[j] such that j > i and A[j] > A[i] and the value of j should be as minimum as possible. If the next greater element doesn’t exist in the array for any element, consider it -1.

For example,

The idea is to use two nested loops. The outer loop takes each element of the array from left to right. The inner loop considers all elements to the “right” of the element picked by the outer loop. Terminate the inner loop as soon as the first larger element is found, which would be the next greater element for the element picked by the outer loop.
The time complexity of this approach is O(n2). Below is the implementation in C, Java, and Python based on the above idea.

C

Download   Run Code

Output:

7 8 5 6 6 8 -1

Java

Download   Run Code

Output:

7 8 5 6 6 8 -1

Python

Download   Run Code

Output:

7 8 5 6 6 8 -1

Download   Run Code
Output:

7 8 5 6 6 8 -1

Download   Run Code
Output:

7 8 5 6 6 8 -1

Download   Run Code
Output:

7 8 5 6 6 8 -1

The time complexity can be easily reduced to linear by using extra space. The idea is to use a stack data structure.

Following is the C++, Java, and Python program that demonstrates this algorithm. Note that we’re pushing indexes into the stack instead of the actual elements. Now the next greater element can be set for the popped elements using their index.

C++

Download   Run Code

Output:

7 8 5 6 6 8 -1

Java

Download   Run Code

Output:

[7, 8, 5, 6, 6, 8, -1]

Python

Download   Run Code

Output:

[7, 8, 5, 6, 6, 8, -1]

Download   Run Code
Output:

7 8 5 6 6 8 -1

Download   Run Code
Output:

[7, 8, 5, 6, 6, 8, -1]

Download   Run Code
Output:

[7, 8, 5, 6, 6, 8, -1]

Here’s another stack-based solution where elements are processed from right to left in the array.

Following is the C++, Java, and Python program that demonstrates this algorithm.

C++

Download   Run Code

Output:

7 8 5 6 6 8 -1

Java

Download   Run Code

Output:

[7, 8, 5, 6, 6, 8, -1]

Python

Download   Run Code

Output:

[7, 8, 5, 6, 6, 8, -1]

Download   Run Code
Output:

7 8 5 6 6 8 -1

Download   Run Code
Output:

[7, 8, 5, 6, 6, 8, -1]

Download   Run Code
Output:

[7, 8, 5, 6, 6, 8, -1]

The time complexity of both stack-based solutions is O(n) since every element is pushed and popped at most once to the stack. The auxiliary space used is O(n) for the stack.

Exercise: Extend the solution for a circular array to search circularly to find the next greater element.

source