Next Greater Element
Problem
For each element print the first element to its right that is strictly greater. If there is none, print -1.
Constraints
- 1 <= n <= 10^5
Examples
Input
5 2 1 2 4 3
Output
4 2 4 -1 -1
Solutions
A stack of waiting elements stays in decreasing order. A new bigger element answers all smaller waiting elements at the top. Every index is pushed and popped once, so the time is O(n).
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The next greater values.
* Approach: A monotonic stack.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
int[] result = new int[a.length];
java.util.Arrays.fill(result, -1);
// Step 1: The stack keeps the indexes of elements that still wait for a greater element.
java.util.ArrayDeque<Integer> stack = new java.util.ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
// Step 2: The current element is greater than the waiting ones on top. It is their answer.
while (!stack.isEmpty() && a[stack.peek()] < a[i]) {
int waiting = stack.pop();
result[waiting] = a[i];
}
// Step 3: The current element now waits for its own answer.
stack.push(i);
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Which elements are waiting on the stack?