# Next greater element in same order as input in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 and an array.

• Iterate from the end of the array.

• Remove the elements from the stack until it empty and the top element is less than or equal to the current element.

• If the stack is empty, then there is no next greater element. So add -1 to the result array.

• If the stack is not empty, then the top element is the next greater element for the current element. Add it to the result array.

• Push the current element to the stack.

• Iterate over the result array and print each element along with its next greater element.

## Implementation

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

#include <bits/stdc++.h>
using namespace std;
void nextGreaterElements(int arr[], int n) {
stack<int> s;
int result[n];
for (int i = n - 1; i >= 0; i--) {
while (!s.empty() && s.top() <= arr[i]) {
s.pop();
}
if (s.empty()) {
result[i] = -1;
}else {
result[i] = s.top();
}
s.push(arr[i]);
}
for (int i = 0; i < n; i++) {
cout << arr[i] << " -> " << result[i] << endl;
}
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
int n = 5;
nextGreaterElements(arr, n);
return 0;
}

## Output

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

1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> -1