Next Greater Element on a Stream
Problem statement
Numbers arrive one at a time. stream[i] is the number that arrives at step i, counting from 0. The next greater element of the number at step j is the first number that arrives after step j and is strictly greater than stream[j].
Process the numbers in arrival order. When the number at step i arrives, report every earlier step j whose next greater element is stream[i]. These are exactly the steps whose answer becomes known at step i.
Return an array answer of length stream.length, where answer[i] lists those steps j in increasing order. A step whose number is never followed by a greater number is never reported.
Try to process each number as it arrives, keeping in memory only the steps whose answer is still unknown.
Function
streamNextGreater(stream: int[]) → int[][]Examples
Example 1
stream = [2,1,3,2,5]return = [[],[],[0,1],[],[2,3]]Steps 0 and 1 bring 2 and 1. Nothing earlier is smaller, so nothing is reported.
Step 2 brings 3, which is the first greater number after 2 (step 0) and after 1 (step 1), so it reports [0,1]. Step 3 brings 2, which is not greater than 3.
Step 4 brings 5, which answers step 2 (value 3) and step 3 (value 2), so it reports [2,3].
Example 2
stream = [5,4,4,6]return = [[],[],[],[0,1,2]]The second 4 is not greater than the first 4, so it answers nothing. The 6 at step 3 is the first greater number for all three earlier steps.
Example 3
stream = [3,3,1]return = [[],[],[]]No number is ever followed by a strictly greater one, so every step reports an empty list.
Example 4
stream = [1,2,3]return = [[],[0],[1]]Each number answers only the step right before it. When 3 arrives, step 0 was already answered by 2, so step 2 reports only [1].
Constraints
1 <= stream.length <= 10^5-10^9 <= stream[i] <= 10^9