Next Greater Element in C++

The next greater element is the element that is first greater element after it. Let's see an example.

arr = [4, 5, 3, 2, 1]

The next greater element for 4 is 5 and the next greater element for elements 3, 2, 1 is -1 as there is no greater element after them.

Algorithm

  • Initialise the array with random numbers.

  • Initialise a stack.

  • Add first element to the stack.

  • Iterate through the element of the array.

    • If the stack is empty, add the current element to the stack.

    • While the current element is greater than the top element of the stack.

      • Print the top element with the next greater element as current element.

      • Pop the top element.

    • Add the element to the stack.

  • While stack is not empty.

    • Print the elements with next greater element as -1.

Implementation

Following is the implementation of the above algorithm in C++

#include 
using namespace std;
void nextGreaterElements(int arr[], int n) {
   stack s;
   s.push(arr[0]);
   for (int i = 1; i  "  " 

Output

If you run the above code, then you will get the following result.

1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> -1
Updated on: 2021-10-23T18:16:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements