For each node in a singly linked list, find the value of the first node to its right that is strictly larger.
Next Greater Node in Linked List
gfgProblem
Given the head of a singly linked list, compute an answer for every node.
For the node at position i, look to the nodes that appear after it in the list and return the value of the first node whose value is strictly greater than the current node value. If no such node exists, the answer for that position is 0.
Return the answers in the same order as the nodes appear in the list.
Notes
- The list is singly linked, so you can only move forward through it.
- The "next greater" node for a position is the first later node with a larger value, not necessarily the maximum value to the right.
Input Format
- A singly linked list represented by its head node.
Output Format
- An array of integers where the
i-th value is the next greater value for thei-th list node, or0if none exists.
Constraints
- The list length is at least 1.
- Node values are integers.
- The list size is small enough to require an efficient solution better than checking every pair in the worst case.
Hints
- Think about how to remember nodes whose next greater value has not been found yet.
- A stack that keeps values in decreasing order can help resolve multiple nodes at once.
- If the linked list makes random access awkward, you may first collect values into a linear structure and then process them.
Input Format
A singly linked list head.
Output Format
An integer array containing the next greater value for each node, in order.
Constraints
- At least one node is present.
- Return
0when no greater value exists to the right. - Use only values from later nodes; the current node does not count.
Example 1
Input
head = [2,1,5]
Output
[5,5,0]
Explanation
For 2, the first larger value to the right is 5. For 1, it is also 5. For 5, none exists, so the answer is 0.
Example 2
Input
head = [2,7,4,3,5]
Output
[7,0,5,5,0]
Explanation
- 2 -> 7
- 7 -> no larger value to the right
- 4 -> 5
- 3 -> 5
- 5 -> none
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.