Next Greater Node In Linked List (LeetCode 1019): Solution and Explanation

Medium
Array
Linked List
Stack
Monotonic Stack

Given the head of a linked list, return an array where entry i is the value of the first node after node i that is strictly larger, or 0 if there is none.

Intuition

The direct approach looks right from every node until it finds something bigger. On a decreasing list that is n squared comparisons, and with 10,000 nodes it does far more work than needed.

Turn the question around. Instead of each node searching forward, let each new value answer the earlier nodes that are still waiting. When value v arrives, every waiting node smaller than v has just found its answer.

Which nodes are waiting? Exactly the ones that have not seen a bigger value yet. Among them, values never increase from older to newer, because a bigger newer value would already have answered the smaller older one. That ordering is a stack: the smallest waiting values sit on top, right where v meets them first.

A singly linked list cannot be indexed, so copy the values into an array first. Then the stack can hold indices and write the answers straight into the result array.

Approach: Monotonic stack

  1. Walk the list and copy every value into vals.
  2. Create answer filled with zeros and an empty stack of indices.
  3. For each index i with value v, while the stack is not empty and vals[stack.top] < v, pop the top and set answer[top] = v.
  4. Push i onto the stack; it now waits for a larger value.
  5. Return answer. Indices still on the stack never found a larger value and keep 0.

Step-by-step example

head = [2,1,5]
  1. Copy the list: vals = [2,1,5], answer = [0,0,0].
  2. i = 0, v = 2: the stack is empty, push 0. Stack holds value 2.
  3. i = 1, v = 1: the top value 2 is not smaller than 1, so push 1. Stack holds values 2, 1.
  4. i = 2, v = 5: top value 1 < 5, pop it and set answer[1] = 5. Next top 2 < 5, pop it and set answer[0] = 5. Push 2.
  5. The scan ends with index 2 still waiting, so answer[2] stays 0. Result [5,5,0].

Code: Python, Java, C++

1class Solution:
2    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
3        vals = []
4        while head:
5            vals.append(head.val)
6            head = head.next
7        answer = [0] * len(vals)
8        stack = []
9        for i, v in enumerate(vals):
10            while stack and vals[stack[-1]] < v:
11                answer[stack.pop()] = v
12            stack.append(i)
13        return answer
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Monotonic stack O(n)
Right-to-left stack O(n)
Scan right from every node O(n²)
Time

O(n)

Copying the list is one pass. In the scan every index is pushed once and popped at most once, so the total stack work is linear.

Space

O(n)

The value array, the answer array and the stack can each hold up to n entries.

Other approaches

Scan right from every node (time O(n²), space O(1) extra)

For each node, walk forward until a larger value appears. It is easy to write and correct, but a decreasing list makes it quadratic.

Right-to-left stack (time O(n), space O(n))

Scan from the end, keeping a stack of candidate values. Pop values that are not larger than the current one; the remaining top is the answer. It needs the values in an array too and has the same O(n) cost.

Common mistakes

  • Using <= instead of < when popping. Equal values are not greater, so a node with the same value must not answer an earlier one.
  • Storing values on the stack instead of indices. You then cannot tell which position in answer to fill.
  • Trying to index the linked list directly. Copy it into an array first, or track node positions as you walk.
  • Forgetting that nodes left on the stack must report 0. Initializing answer with zeros handles them for free.

Frequently asked questions

Why is the stack monotonic?

A value stays on the stack only while nothing larger has appeared after it. If a newer value were larger than an older one still on the stack, the older one would have been popped when the newer one arrived. So from bottom to top the values never increase.

Can I solve it without copying the list into an array?

Yes. Keep a stack of (index, value) pairs and grow the answer list as you walk the nodes. It is the same algorithm; copying first just keeps the code short.

What is the time complexity?

O(n). Each index enters and leaves the stack at most once, so the inner while loop does O(n) work across the whole scan.

How does this relate to Next Greater Element and Daily Temperatures?

They are the same pattern. Daily Temperatures stores the distance to the next greater value instead of the value itself, and Next Greater Element II walks a circular array twice.