For each element in an array, find the next element to its right that is greater; use -1 when none exists (e.g. [2,1,3] -> [3,3,-1]).
A monotonic decreasing stack of indices solves this in one pass: for each element, pop every index whose value is smaller (the current element is their answer), then push the current index. Any indices left on the stack have no greater element. O(n) time — each index is pushed and popped once.
public static int[] nextGreater(int[] a) {
int[] res = new int[a.length];
java.util.Arrays.fill(res, -1);
Deque<Integer> stack = new ArrayDeque<>(); // indices
for (int i = 0; i < a.length; i++) {
while (!stack.isEmpty() && a[i] > a[stack.peek()])
res[stack.pop()] = a[i];
stack.push(i);
}
return res;
}function nextGreater(a) {
const res = new Array(a.length).fill(-1);
const stack = []; // indices
for (let i = 0; i < a.length; i++) {
while (stack.length && a[i] > a[stack[stack.length - 1]])
res[stack.pop()] = a[i];
stack.push(i);
}
return res;
}def next_greater(a):
res = [-1] * len(a)
stack = [] # indices
for i, x in enumerate(a):
while stack and x > a[stack[-1]]:
res[stack.pop()] = x
stack.append(i)
return resThe monotonic-stack pattern powers stock-span, daily-temperatures, and histogram problems — anywhere you need the nearest larger/smaller neighbor efficiently.
A candidate uses nested loops (O(n^2)). What is the key idea that makes it O(n)?