You are given the head of a linked list with n nodes. For each node, find the value of the first node after it that has a strictly larger value. Return an integer array answer where answer[i] is that value for the i-th node (1-indexed in the statement, 0-indexed in the array), or 0 if no such node exists.
You are given the head of a linked list with n nodes. For each node, find the value of the first node after it that has a strictly larger value. Return an integer array answer where answer[i] is that value for the i-th node (1-indexed in the statement, 0-indexed in the array), or 0 if no such node exists.
Example 1:
Input: {"head":[2,1,5]}
Output: [5,5,0]
Constraints:
The number of nodes in the list is n.
1≤n≤104
1≤Node.val≤109
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"head":[2,1,5]}
For every node we need the first value to its right that is strictly larger. A list only walks forward, so first copy the values into an array.
the list (bar height = value), answer under each node
2
·
#0
→
1
·
#1
→
5
·
#2
current node
stack top compared
waiting on stack
just answered
monotonic stack: nodes still waiting (bottom → top, values never increase)