C++ Program To Find Next Greater Element
Last Updated :
17 Aug, 2023
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1.
Examples:
- For an array, the rightmost element always has the next greater element as -1.
- For an array that is sorted in decreasing order, all elements have the next greater element as -1.
- For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.
Element NGE
4 --> 5
5 --> 25
2 --> 25
25 --> -1
d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.
Element NGE
13 --> -1
7 --> 12
6 --> 12
12 --> -1
Method 1 (Simple)
Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by the outer loop. If a greater element is found then that element is printed as next, otherwise, -1 is printed.
Below is the implementation of the above approach:
C++
// Simple C++ program to print
// next greater elements in a
// given array
#include<iostream>
using namespace std;
/* prints element and NGE pair
for all elements of arr[] of size n */
void printNGE(int arr[], int n)
{
int next, i, j;
for (i = 0; i < n; i++)
{
next = -1;
for (j = i + 1; j < n; j++)
{
if (arr[i] < arr[j])
{
next = arr[j];
break;
}
}
cout << arr[i] << " -- "
<< next << endl;
}
}
// Driver Code
int main()
{
int arr[] = {11, 13, 21, 3};
int n = sizeof(arr)/sizeof(arr[0]);
printNGE(arr, n);
return 0;
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Output11 -- 13
13 -- 21
21 -- -1
3 -- -1
Time Complexity: O(N2)
Auxiliary Space: O(1)
Method 2 (Using Stack)
- Push the first element to stack.
- Pick rest of the elements one by one and follow the following steps in loop.
- Mark the current element as next.
- If stack is not empty, compare top element of stack with next.
- If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.
- Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
- Finally, push the next in the stack.
- After the loop in step 2 is over, pop all the elements from the stack and print -1 as the next element for them.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
// A Stack based C++ program to find next
// greater element for all array elements.
#include <bits/stdc++.h>
using namespace std;
/* prints element and NGE pair for all
elements of arr[] of size n */
void printNGE(int arr[], int n)
{
stack<int> s;
/* push the first element to stack */
s.push(arr[0]);
// iterate for rest of the elements
for (int i = 1; i < n; i++)
{
if (s.empty()) {
s.push(arr[i]);
continue;
}
/* if stack is not empty, then
pop an element from stack.
If the popped element is smaller
than next, then
a) print the pair
b) keep popping while elements are
smaller and stack is not empty */
while (s.empty() == false
&& s.top() < arr[i])
{
cout << s.top()
<< " --> " << arr[i] << endl;
s.pop();
}
/* push next to stack so that we can find
next greater for it */
s.push(arr[i]);
}
/* After iterating over the loop, the remaining
elements in stack do not have the next greater
element, so print -1 for them */
while (s.empty() == false) {
cout << s.top() << " --> " << -1 << endl;
s.pop();
}
}
/* Driver code */
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printNGE(arr, n);
return 0;
}
Output11 --> 13
13 --> 21
3 --> -1
21 --> -1
Time Complexity: O(N)
Auxiliary Space: O(N)
The worst case occurs when all elements are sorted in decreasing order. If elements are sorted in decreasing order, then every element is processed at most 4 times.
- Initially pushed to the stack.
- Popped from the stack when next element is being processed.
- Pushed back to the stack because the next element is smaller.
- Popped from the stack in step 3 of the algorithm.
How to get elements in the same order as input?
The above approach may not produce output elements in the same order as the input. To achieve the same order, we can traverse the same in reverse order
Below is the implementation of the above approach:
C++
// A Stack based C++ program to find next
// greater element for all array elements
// in same order as input.
#include <bits/stdc++.h>
using namespace std;
/* prints element and res pair for all
elements of arr[] of size n */
void printNGE(int arr[], int n)
{
stack<int> s;
int res[n];
for (int i = n - 1; i >= 0; i--) {
/* if stack is not empty, then
pop an element from stack.
If the popped element is smaller
than next, then
a) print the pair
b) keep popping while elements are
smaller and stack is not empty */
if (!s.empty()) {
while (!s.empty() && s.top() <= arr[i]) {
s.pop();
}
}
res[i] = s.empty() ? -1 : s.top();
s.push(arr[i]);
}
for (int i = 0; i < n; i++)
cout << arr[i] << " --> " << res[i] << endl;
}
// Driver Code
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
printNGE(arr, n);
return 0;
}
Output11 ---> 13
13 ---> 21
21 ---> -1
3 ---> -1
Time Complexity: O(N)
Auxiliary Space: O(N)
Please see for an optimized solution for printing in same order.
Please refer complete article on
Next Greater Element for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read