Basic example
Input
[4, 5, 2, 25]
Output
[5, 25, 25, -1]
For 4 the next greater is 5; for 5 it's 25; for 2 it's 25; for 25 there is none.
Full lesson preview
For each element in an array, find the next greater element to its right. Use a stack to solve in linear time.
Problem statement
Task
Examples
Input
[4, 5, 2, 25]
Output
[5, 25, 25, -1]
For 4 the next greater is 5; for 5 it's 25; for 2 it's 25; for 25 there is none.
Input format
Output format
Constraints
Samples
Input
[1, 3, 2, 4]
Output
[3, 4, 4, -1]
Next greater for 1 is 3, for 3 is 4, for 2 is 4, for 4 none.