Next Greater Node In Linked List - Problem
You're given the head of a singly linked list with n nodes. Your mission is to find the next greater element for each node in the list.
For each node, you need to find the first node that comes after it and has a strictly larger value. If no such node exists, the answer for that position should be 0.
Return an integer array answer where answer[i] represents the value of the next greater node for the i-th node (1-indexed). This is a classic example of the "Next Greater Element" pattern, but with the added challenge of working with a linked list structure.
Example: For linked list 2 โ 1 โ 5, the answer would be [5, 5, 0] because:
- Node 2: Next greater is 5
- Node 1: Next greater is 5
- Node 5: No next greater element exists
Input & Output
example_1.py โ Basic Case
$
Input:
head = [2,1,5]
โบ
Output:
[5,5,0]
๐ก Note:
For node with value 2: next greater is 5. For node with value 1: next greater is 5. For node with value 5: no next greater element exists.
example_2.py โ Increasing Sequence
$
Input:
head = [1,7,5,1,9,2,5,1]
โบ
Output:
[7,9,9,9,0,5,0,0]
๐ก Note:
Each element finds its next greater element or gets 0 if none exists. For example, 7's next greater is 9, 5's next greater is 9, etc.
example_3.py โ Single Element
$
Input:
head = [5]
โบ
Output:
[0]
๐ก Note:
Single element has no next element, so result is [0].
Constraints
- The number of nodes in the linked list is in the range [0, 104]
- 1 โค Node.val โค 109
- Note: The result should be 1-indexed as per the problem description
Visualization
Tap to expand
Understanding the Visualization
1
Convert to Array
Transform linked list [2โ1โ5] into array [2,1,5] for easier processing
2
Initialize Stack
Create empty stack to store indices of elements waiting for next greater element
3
Process Elements
For each element, pop smaller elements from stack (they found their answer) and push current index
4
Handle Remaining
Elements still in stack have no next greater element, so their result stays 0
Key Takeaway
๐ฏ Key Insight: The monotonic stack pattern allows us to solve "next greater element" problems in O(n) time by maintaining pending queries efficiently and resolving multiple queries when we find a larger element.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code