Find the Next Greater Element for Every Element

In this tutorial, we will write the Python program to find the next greater element for every element in the given array. The "Next Greater Element" for a given element x refers to the first element on the right side of x in the array that is greater than x. If there is no greater element to the right of x, it is considered as -1.

Let's understand the following example -

Example:

Input:

arr[] = [3, 8, 4, 10, 6]

Output: 3 -> 8

8 -> 10

4 -> 10

10 -> -1

6 -> -1

Explanation: In this example, for each element in the array, we find the next greater element on its right side. The output shows the mapping of elements to their next greater elements. Elements 10 and 6 don't have any greater elements on their right side.

Solution - 1:

In this approach, we will use the two for loops, the outer loop will traverse the elements one by one and the inner loop checks the first greater element for the element picked by the outer loop. Then we check the condition if a greater element is found then that element is printed as next, otherwise, -1 is printed.

Let's understand the following example -

Example -

Output

11 --> 13
13 --> 21
21 --> -1
3 --> -1

Explanation -

In the above code, we have followed the below steps -

  1. First, we start with the first element in the array and iterate through the array from left to right.
  2. For each element, initiate another loop that begins from the element's index + 1 and continues to the end of the array.
  3. Inside this inner loop, check if there is a greater element than the current element.
  4. If a greater element is found, print it and exit the inner loop.
  5. If no greater element is found during the inner loop, print -1 to indicate that there is no greater element on the right side of the current element.

Time Complexity: O(N2)

Auxiliary Space: O(1)

Solution - 2: Find Next Greater Element using Stack

The concept involves using a stack to keep track of elements for which we need to find the next greater element. While iterating through the array, when we encounter a greater element, we'll associate it with the elements from the stack until the top element of the stack is smaller than the current element.

Let's understand the following example -

Example -

Output

[5, 10, 10, -1, -1]

Conclusion

In this tutorial, we explored two solutions for finding the next greater element for each element in an array. The first solution used nested loops with a time complexity of O(N^2), while the second solution employed a stack, resulting in a more efficient O(N) time complexity. Using a stack is a practical approach for solving such problems, offering improved performance.