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<sup>th</sup>
node (1-indexed). If the i<sup>th</sup>
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^4
1 <= Node.val <= 10^9
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
# Convert linked list to array
A = []
curr = head
while curr:
A.append(curr.val)
curr = curr.next
n = len(A)
ans = [0] * n
stack = [] # Monotonic decreasing stack
for i in range(n):
# While the stack is not empty and the current element is greater than the top of the stack
while stack and A[i] > A[stack[-1]]:
# Pop the top of the stack and set the answer for that index to the current element
ans[stack.pop()] = A[i]
# Push the current index onto the stack
stack.append(i)
return ans
A
. This makes it easier to access elements by index.ans
: An array of the same length as A
, initialized with zeros. This array will store the next greater node for each element.stack
: A stack to store indices of elements in A
. This stack is used to maintain a decreasing order of elements.A
using a for
loop.i
and j
in the stack, if i
is below j
in the stack, then A[i] >= A[j]
.A[i]
is greater than the element at the index on the top of the stack (A[stack[-1]]
), it means that A[i]
is the next greater node for the element at the index on the top of the stack.ans
array is updated to A[i]
.i
is pushed onto the stack to maintain the decreasing order.ans
array, containing the next greater node for each element in the linked list, is returned.Let's walk through an example with the input head = [2, 1, 5]
.
A = [2, 1, 5]
ans = [0, 0, 0]
, stack = []
i = 0
, A[i] = 2
. Stack is empty, so push 0
onto the stack. stack = [0]
i = 1
, A[i] = 1
. A[i] < A[stack[-1]]
(1 < 2), so push 1
onto the stack. stack = [0, 1]
i = 2
, A[i] = 5
. A[i] > A[stack[-1]]
(5 > 1), so pop 1
from the stack and set ans[1] = 5
. stack = [0]
. Now A[i] > A[stack[-1]]
(5 > 2), so pop 0
from the stack and set ans[0] = 5
. stack = []
. Push 2
onto the stack. stack = [2]
ans = [5, 5, 0]