Problem 1019

Abstract / Summary

Given a linked list, for each node find the first node with a larger value that appears after it in the list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1019.py

class Solution:
    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
        result = []

        pos  = 0
        seen = []
        while head:
            heappush(seen, ( head.val, len(result) ))
            result.append(0) #  no bigger node known so far

            while seen:
                # check current node against min-heap
                value, where = seen[0]
                if value >= head.val:
                    break

                # update previous nodes that carry a smaller value
                result[where] = head.val
                heappop(seen)

            head = head.next

        return result
23 lines | 673 bytes | submitted October 16, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Linked List
  • Monotonic Stack
  • Stack
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “next greater node in a linked list” problem by walking the list once while maintaining a min-heap of nodes whose next larger value has not yet been discovered. For each node the algorithm records a placeholder in the output list, pushes the node’s value together with its position onto the heap, and then repeatedly pops from the heap any entries whose stored value is smaller than the current node’s value. When a pop occurs the corresponding position in the result list is updated with the current node’s value, which is the first larger value seen for that earlier node. The traversal finishes when the end of the linked list is reached, leaving any remaining heap entries with a zero (the initialized placeholder) because no larger node exists later in the list.

Initialization

The function begins by creating an empty list that will hold the final answers. Two auxiliary variables are also prepared: an integer pos that tracks the index of the node being processed (although it is not used later) and a list seen that will serve as the underlying container for the heap.

result = []
pos  = 0
seen = []

The result list grows in lockstep with the traversal, guaranteeing that the index stored in the heap always points to a valid entry.

Traversal and heap insertion

The outer while head: loop iterates over each node of the linked list. For the current node the algorithm pushes a tuple containing the node’s value and the current length of result onto the heap. The length of result at this moment is exactly the index where the placeholder for this node will be stored. Immediately after the push a zero is appended to result to indicate that a larger node has not yet been found.

while head:
    heappush(seen, (head.val, len(result)))
    result.append(0)   # no bigger node known so far

Because the heap is a min-heap, the smallest pending value is always at seen[0]. This property enables the inner loop to focus only on entries that can be resolved by the current node.

Resolving pending nodes

Inside the outer loop, a nested while seen: loop checks whether the smallest value in the heap is strictly less than the current node’s value. If it is, that means the current node is the first larger node for the earlier entry. The algorithm extracts the stored index (where) and writes the current node’s value into the corresponding position of result. The heap entry is then removed with heappop. This process repeats until the smallest pending value is no longer smaller than the current node’s value, at which point the inner loop exits.

while seen:
    value, where = seen[0]
    if value >= head.val:
        break
    result[where] = head.val
    heappop(seen)

By always comparing against the minimum pending value, the algorithm guarantees that each earlier node is updated exactly once, at the moment its next larger node appears.

Advancing the pointer

After the inner loop finishes, the traversal proceeds to the next node in the linked list. The head reference is simply moved forward.

head = head.next

When the outer loop terminates, every node has either been updated with a larger value or retained the initial zero, which correctly represents the absence of a larger successor.

Edge-case handling

The code naturally accommodates an empty linked list because the outer while head: loop never executes, leaving result as an empty list that is returned. For a single-node list the heap receives one entry, the inner loop never pops it (no larger value exists), and the final result contains a single zero, correctly indicating that there is no greater node.

In a strictly decreasing sequence each new node is smaller than all previously seen nodes, so the inner loop never triggers a pop; every position in result remains zero, which matches the expected output.

Conversely, for a strictly increasing sequence each new node is larger than all pending entries. The inner loop will repeatedly pop all earlier nodes, updating each of their result positions with the current value. By the time the traversal ends, only the last node’s placeholder stays zero, reflecting that it has no larger successor.

When duplicate values appear, the condition value >= head.val ensures that nodes with equal values are not considered larger, so they remain unresolved until a strictly greater value is encountered. This respects the problem’s definition of “greater” rather than “greater or equal”.

Performance optimizations

The algorithm achieves a single-pass solution by coupling the traversal with a heap that stores only those nodes awaiting a larger value. The use of a min-heap means that each insertion and removal costs logarithmic time relative to the number of pending nodes, but because each node is inserted once and removed at most once, the total work scales efficiently with the list length.

Updating the result list in place avoids the need for auxiliary structures to map indices back to nodes, and the direct use of len(result) as the index eliminates an extra counter variable. The early-exit condition if value >= head.val: break prevents unnecessary heap inspections once the smallest pending value can no longer be satisfied by the current node, reducing the number of comparisons.

By initializing each entry of result to zero immediately after pushing the node onto the heap, the algorithm guarantees that the output list is fully populated without a separate post-processing pass. This in-place construction eliminates extra memory allocation and copying that a two-phase approach would require.

Overall, the design leverages the heap’s ordering property to resolve pending nodes precisely when their next larger value becomes available, delivering an elegant and efficient solution without redundant scans.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of toy trains sitting on a track, where each train has a number written on its side. Your task is to look at each train and figure out which one is the very next train down the line that has a bigger number.

To do this, there is a special box called seen. When a train comes along, it puts its number and its spot in the line into this box. But because the box is clever, it always keeps the train with the smallest number right at the very front.

Every time a new train arrives, it peeks at the front of the box. If the train in the box has a smaller number than the new train, it means the new train is the bigger neighbor that the older train was looking for. So, the old train gets the new number written down next to it, and then it is taken out of the box. This happens over and over again until the new train finds someone in the box that is bigger than itself. After that, the new train takes its own turn waiting in the box, and the process repeats for the next train in line. If a train gets to the end and nobody in the box was bigger, that spot just stays as a zero because it never found its bigger friend.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.07 | σ = 1.74

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
fartem Ruby
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fartem Ruby
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
35 links | 20 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   October 16, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality