Next Greater Node In Linked List Problem
Description
LeetCode Problem 1019.
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.
Example 1:

Input: head = [2,1,5]
Output: [5,5,0]
Example 2:

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]
Constraints:
- The number of nodes in the list is
n. 1 <= n <= 10^41 <= Node.val <= 10^9
Solution
Approach: Monotonic Stack
Checking every node against all the nodes after it takes O(n2) time. This is the classic "next greater element" question, so we copy the list's values into an array and solve it there with a stack.
Walk the array from right to left and keep a stack of values that could still be someone's answer. For the value x at index i:
- Pop every value on top of the stack that is
<= x. Such a value can never be the answer for anything left ofi, becausexcomes earlier and is at least as large. - Whatever is left on top is the first value to the right of
ithat is strictly larger thanx; if the stack is empty, the answer is0. - Push
x.
The stack stays strictly decreasing from bottom to top. Note the <= when popping: the problem wants a strictly larger value, so equal values must be popped too (for [5,5] the answer is [0,0], not [5,0]).
Complexity: O(n) time, since every value is pushed and popped at most once, and O(n) extra space for the array and the stack.
class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
values = []
while head:
values.append(head.val)
head = head.next
answer = [0] * len(values)
stack = [] # values to the right of i, strictly decreasing from bottom to top
for i in range(len(values) - 1, -1, -1):
while stack and stack[-1] <= values[i]:
stack.pop() # not larger than values[i], so never the answer for anything left of i
if stack:
answer[i] = stack[-1]
stack.append(values[i])
return answer