Problem 126
Next Greater Element
Medium · 20 pts · Array, Stack, Monotonic Stack
Problem
You are given an array of N integers. For each element, find the next greater element: the first element to its right that is strictly greater than it. Print these values in order, using -1 for elements that have no greater element to their right (the last element always gets -1). A monotonic stack solves this in O(N): scan from left to right while keeping a stack of elements still waiting for their answer. Each new element pops every smaller element from the stack and becomes their answer.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print N values, space-separated.
Constraints
1 <= N <= 100000; 0 <= A[i] <= 1000000000
Example input
4 4 5 2 25
Example output
5 25 25 -1
Explanation
For 4 5 2 25: the first value larger than 4 to its right is 5; for 5 it is 25; for 2 it is also 25; and nothing comes after 25, so it gets -1. The output is 5 25 25 -1.