Next Greater Node In Linked List (LeetCode 1019): Solution and Explanation
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
- Walk the list and copy every value into
vals. - Create
answerfilled with zeros and an emptystackof indices. - For each index
iwith valuev, while the stack is not empty andvals[stack.top] < v, pop the top and setanswer[top] = v. - Push
ionto the stack; it now waits for a larger value. - Return
answer. Indices still on the stack never found a larger value and keep 0.
Step-by-step example
head = [2,1,5]
- Copy the list:
vals= [2,1,5],answer= [0,0,0]. - i = 0, v = 2: the stack is empty, push 0. Stack holds value 2.
- i = 1, v = 1: the top value 2 is not smaller than 1, so push 1. Stack holds values 2, 1.
- i = 2, v = 5: top value 1 < 5, pop it and set
answer[1]= 5. Next top 2 < 5, pop it and setanswer[0]= 5. Push 2. - 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 answer1class Solution {
2 public int[] nextLargerNodes(ListNode head) {
3 List<Integer> vals = new ArrayList<>();
4 while (head != null) {
5 vals.add(head.val);
6 head = head.next;
7 }
8 int[] answer = new int[vals.size()];
9 Deque<Integer> stack = new ArrayDeque<>();
10 for (int i = 0; i < vals.size(); i++) {
11 int v = vals.get(i);
12 while (!stack.isEmpty() && vals.get(stack.peek()) < v) {
13 answer[stack.pop()] = v;
14 }
15 stack.push(i);
16 }
17 return answer;
18 }
19}1class Solution {
2public:
3 vector<int> nextLargerNodes(ListNode* head) {
4 vector<int> vals;
5 while (head) {
6 vals.push_back(head->val);
7 head = head->next;
8 }
9 vector<int> answer(vals.size(), 0);
10 vector<int> stk;
11 for (int i = 0; i < (int)vals.size(); i++) {
12 while (!stk.empty() && vals[stk.back()] < vals[i]) {
13 answer[stk.back()] = vals[i];
14 stk.pop_back();
15 }
16 stk.push_back(i);
17 }
18 return answer;
19 }
20};Time and space complexity
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.
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
answerto 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
answerwith 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.