Next Greater Node In Linked List - Problem

You are given the head of a linked list with n nodes.

For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.

Return an integer array answer where answer[i] is the value of the next greater node of the i-th node (1-indexed). If the i-th node does not have a next greater node, set answer[i] = 0.

Input & Output

Example 1 — Basic Case
$ Input: head = [2,1,5]
Output: [5,5,0]
💡 Note: For node 2: next greater is 5. For node 1: next greater is 5. For node 5: no next greater, so 0.
Example 2 — Increasing Sequence
$ Input: head = [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]
💡 Note: Each node finds its next greater element: 1→7, 7→9, 5→9, 1→9, 9→none, 2→5, 5→none, 1→none.
Example 3 — Decreasing Sequence
$ Input: head = [5,4,3,2,1]
Output: [0,0,0,0,0]
💡 Note: No node has a next greater element since the sequence is strictly decreasing.

Constraints

  • The number of nodes in the list is in the range [1, 104]
  • 1 ≤ Node.val ≤ 109

Visualization

Tap to expand
Next Greater Node In Linked List INPUT Linked List Structure: 2 i=0 1 i=1 5 i=2 NULL Input Array: head = [2, 1, 5] Find next greater for each: 2 --> ? | 1 --> ? | 5 --> ? Use Monotonic Stack Track indices of nodes waiting for greater value ALGORITHM STEPS 1 Convert to Array Traverse list, store values vals = [2, 1, 5] 2 Initialize Stack + Result stack=[], result=[0,0,0] 3 Iterate Left to Right Pop smaller, update result i=0, val=2: stack=[0] i=1, val=1: stack=[0,1] i=2, val=5: pop 1: result[1]=5 pop 0: result[0]=5 stack=[2] (no update for 5) 4 Remaining = 0 Unpopped indices stay 0 FINAL RESULT Next Greater Node Values: 2 5 1 5 5 0 Output Array: [5, 5, 0] Explanation: Node 2: next greater is 5 Node 1: next greater is 5 Node 5: no greater (= 0) OK - Verified! Key Insight: Use a monotonic decreasing stack storing indices. When we find a larger value, pop all smaller elements and update their results. This achieves O(n) time complexity since each element is pushed and popped at most once. Elements remaining in stack have no greater node (answer = 0). TutorialsPoint - Next Greater Node In Linked List | Optimal Solution (Monotonic Stack)
Asked in
Amazon 45 Microsoft 32 Google 28
152.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen