Next greater element in same order as input
Last Updated :
02 Sep, 2022
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 array. Elements for which no greater element exist, consider next greater element as -1. The next greater elements should be printed in same order as input array.
Examples:
Input : arr[] = [4, 5, 2, 25}
Output : 5 25 25 -1
Input : arr[] = [4, 5, 2, 25, 10}
Output : 5 25 25 -1 -1
We have discussed a solution here that does not print same order. Here we traverse array from rightmost element.
- In this approach, we have started iterating from the last element(nth) to the first(1st) element
The benefit is that when we arrive at a certain index his next greater element will be already in the stack, and we can directly get this element while at the same index. - After reaching a certain index we will pop the stack till we get the greater element on top of the current element and that element will be the answer for current element
- If the stack gets empty while doing the pop operation then the answer would be -1
Then we will store the answer in an array for the current index.
Implementation:
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 NGE pair for all
elements of arr[] of size n */
void printNGE(int arr[], int n)
{
stack<int> s;
int arr1[n];
// iterating from n-1 to 0
for (int i = n - 1; i >= 0; i--)
{
/*We will pop till we get the
greater element on top or stack gets empty*/
while (!s.empty() && s.top() <= arr[i])
s.pop();
/*if stack gots empty means there
is no element on right which is greater
than the current element.
if not empty then the next greater
element is on top of stack*/
if (s.empty())
arr1[i] = -1;
else
arr1[i] = s.top();
s.push(arr[i]);
}
for (int i = 0; i < n; i++)
cout << arr[i] << " ---> " << arr1[i] << endl;
}
/* Driver program to test above functions */
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printNGE(arr, n);
return 0;
}
Java
// A Stack based Java program to find next
// greater element for all array elements
// in same order as input.
import java.util.*;
class GfG {
/* prints element and NGE pair for all
elements of arr[] of size n */
static void printNGE(int arr[], int n)
{
Stack<Integer> s = new Stack<Integer>();
int arr1[] = new int[n];
// iterating from n-1 to 0
for (int i = n - 1; i >= 0; i--)
{
/*We will pop till we get the
greater element on top or stack gets empty*/
while (!s.isEmpty() && s.peek() <= arr[i])
s.pop();
/*if stack gots empty means there
is no element on right which is greater
than the current element.
if not empty then the next greater
element is on top of stack*/
if (s.empty())
arr1[i] = -1;
else
arr1[i] = s.peek();
s.push(arr[i]);
}
for (int i = 0; i < n; i++)
System.out.println(arr[i] + " ---> " + arr1[i]);
}
/* Driver program to test above functions */
public static void main(String[] args)
{
int arr[] = { 11, 13, 21, 3 };
int n = arr.length;
printNGE(arr, n);
}
}
Python3
# A Stack based Python3 program to find next
# greater element for all array elements
# in same order as input.
# prints element and NGE pair for all
# elements of arr[] of size n
def printNGE(arr, n):
s = list()
arr1 = [0 for i in range(n)]
# iterating from n-1 to 0
for i in range(n - 1, -1, -1):
# We will pop till we get the greater
# element on top or stack gets empty
while (len(s) > 0 and s[-1] <= arr[i]):
s.pop()
# if stack gots empty means there
# is no element on right which is
# greater than the current element.
# if not empty then the next greater
# element is on top of stack
if (len(s) == 0):
arr1[i] = -1
else:
arr1[i] = s[-1]
s.append(arr[i])
for i in range(n):
print(arr[i], " ---> ", arr1[i] )
# Driver Code
arr = [ 11, 13, 21, 3 ]
n = len(arr)
printNGE(arr, n)
# This code is contributed by Mohit kumar 29
C#
// A Stack based C# program to find next
// greater element for all array elements
// in same order as input.
using System;
using System.Collections.Generic;
class GFG
{
/* prints element and NGE pair for all
elements of arr[] of size n */
static void printNGE(int []arr, int n)
{
Stack<int> s = new Stack<int>();
int []arr1 = new int[n];
// iterating from n-1 to 0
for (int i = n - 1; i >= 0; i--)
{
/*We will pop till we get the
greater element on top or stack gets empty*/
while (s.Count != 0 && s.Peek() <= arr[i])
s.Pop();
/*if stack gots empty means there
is no element on right which is greater
than the current element.
if not empty then the next greater
element is on top of stack*/
if (s.Count == 0)
arr1[i] = -1;
else
arr1[i] = s.Peek();
s.Push(arr[i]);
}
for (int i = 0; i < n; i++)
Console.WriteLine(arr[i] + " ---> " +
arr1[i]);
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 11, 13, 21, 3 };
int n = arr.Length;
printNGE(arr, n);
}
}
// This code is contributed by Ajay Kumar
JavaScript
<script>
// A Stack based Javascript program to find next
// greater element for all array elements
// in same order as input.
// prints element and NGE pair for all
// elements of arr[] of size n
function printNGE(arr, n)
{
let s = [];
let arr1 = new Array(n);
// Iterating from n-1 to 0
for (let i = n - 1; i >= 0; i--)
{
// We will pop till we get the
// greater element on top or
// stack gets empty
while (!s.length == 0 &&
s[s.length - 1] <= arr[i])
s.pop();
// If stack gots empty means there
// is no element on right which is greater
// than the current element.
// if not empty then the next greater
// element is on top of stack
if (s.length == 0)
arr1[i] = -1;
else
arr1[i] = s[s.length - 1];
s.push(arr[i]);
}
for(let i = 0; i < n; i++)
document.write(arr[i] + " ---> " +
arr1[i] + "<br>");
}
// Driver code
let arr = [ 11, 13, 21, 3 ];
let n = arr.length;
printNGE(arr, n);
// This code is contributed by patel2127
</script>
Output11 ---> 13
13 ---> 21
21 ---> -1
3 ---> -1
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n) There is no extra space required if you want to print the next greater of each element in reverse order of input(means first, for the last element and then for second last and so on till the first element)
Similar Reads
Javascript Program To Find Next Greater Element 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 righ
6 min read
Previous greater element Given an array of distinct elements, find previous greater element for every element. If previous greater element does not exist, print -1.Examples: Input : arr[] = {10, 4, 2, 20, 40, 12, 30}Output : -1, 10, 4, -1, -1, 40, 40Input : arr[] = {10, 20, 30, 40}Output : -1, -1, -1, -1Input : arr[] = {40,
11 min read
Next Smaller Element Given an array, print the Next Smaller Element (NSE) for every element. The NSE for an element x is the first smaller element on the right side of x in the array. For elements for which no smaller element exists (on the right side), then consider NSE as -1. Examples:Input: [4, 8, 5, 2, 25]Output: [2
10 min read
Next greater number on the basis of precedence of digits Given a number num containing n digits. The problem is to find the next greater number using the same set of digits in num on the basis of the given precedence of digits. For example the precedence of digits is given as 1, 6, 4, 5, 2, 9, 8, 0, 7, 3 which simply means 1 < 6 < 4 < 5 < 2
9 min read
Sorting all array elements except one Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
6 min read