Next Greater Node In Linked List

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.

30:00

Next Greater Node In Linked List
medium
Free written solution
Topics
Companies

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 nn.

  • 1≤n≤1041 \leq n \leq 10^4

  • 1≤Node.val≤1091 \leq \text{Node.val} \leq 10^9

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)

empty

Variables
VariableValue
i-
v-
stack[]
DepthFunction Call
Stack empty
0/14