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: [2,1,5] → [5,5,0]215Original Linked List2 → next greater: 51 → next greater: 55 → no next greater550Result Array: [5,5,0]
Understanding the Visualization
1
Input
Linked list [2,1,5] - find next greater for each
2
Process
For each node, look ahead to find first greater value
3
Output
Array [5,5,0] - next greater values or 0 if none
Key Takeaway
🎯 Key Insight: Use a monotonic stack to efficiently track elements waiting for their next greater element in O(n) time
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