Problem 148

Abstract / Summary

Given the head of a linked list, return a new linked list that is sorted in ascending order.

Note

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

Python 0148.py

class Solution:
    def bubble(self, head):
        # it's time for the most-hated algorithm: BUBBLESORT !!!
        again = True
        while again:
            again = False
            i = head
            while i.next:
                if i.val > i.next.val:
                    i.val, i.next.val = i.next.val, i.val
                    again = True
                i = i.next
        return head

    def insertion(self, head):
        # should be n log n, doesn't swap Node.val, only manipulates pointers

        done = None
        todo = head
        while todo:
            next = todo.next
            done = self.insertOne(done, todo)
            todo = next
        return done

    def insertOne(self, head, node):
        current = None
        if not head or node.val < head.val:
            node.next = head
            head = node
        else:
            current = head
            while current.next and current.next.val < node.val:
                current = current.next
            node.next = current.next
            current.next = node
        return head

    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head: # size == 0
            return None
        if not head.next: # size == 1
            return head

        size = 0
        i = head
        while i.next:
            size += 1
            i = i.next

        # let's try it hard way, without built-in sort routines ...
        if size < 20:
            head = self.bubble(head)  # O(n^2) ain't bad if n is small
        elif size < 1000:
            head = self.insertion(head)
        else:
            # list manipulation is just too slow, revert to Python's routines
            all = []
            i = head
            while i:
                all.append(i.val)
                i = i.next
            all.sort()
            i = head
            for a in all:
                i.val = a
                i = i.next

        return head

69 lines | 2035 bytes | submitted August 16, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (2+ million submissions).

Typical patterns to solve this problem:
  • Divide And Conquer
  • Linked List
  • Merge Sort
  • Sorting
  • Two Pointers
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 defines a Solution class that offers three distinct sorting strategies for a singly-linked list: a bubble-sort variant that swaps node values, an insertion-sort that rearranges node pointers, and a fallback that extracts values into a Python list, uses the built-in list.sort, and writes the sorted values back into the original nodes. The sortList method selects the appropriate strategy based on the length of the input list, aiming to balance simplicity and performance for different list sizes.

Core Workflow

Size Determination

The algorithm first walks the list to compute its length.

size = 0
i = head
while i.next:
    size += 1
    i = i.next

This traversal stops one node short of the tail, leaving size equal to the number of edges, which is sufficient for the subsequent size-based branching.

Strategy Selection

The size check directs execution to one of three paths:

  • For very small lists (size < 20) the bubble method is invoked.
  • For moderate lists (size < 1000) the insertion method is used.
  • For larger lists the algorithm falls back to a Python list conversion, sorting, and re-injection of values.

Bubble Sort on Node Values

The bubble routine repeatedly scans the list, swapping the val fields of adjacent nodes whenever they are out of order. A flag again tracks whether any swap occurred during a pass; if no swaps happen, the list is sorted and the loop terminates.

again = True
while again:
    again = False
    i = head
    while i.next:
        if i.val > i.next.val:
            i.val, i.next.val = i.next.val, i.val
            again = True
        i = i.next

Insertion Sort via Pointer Manipulation

The insertion method builds a new sorted list (done) by repeatedly extracting the head of the unsorted portion (todo) and inserting it into the correct position using insertOne. The insertion routine walks the already sorted segment until it finds the proper predecessor, then splices the node in place without altering its stored value.

done = None
todo = head
while todo:
    next = todo.next
    done = self.insertOne(done, todo)
    todo = next
return done

The helper insertOne handles insertion at the head when the incoming node is smaller than the current head, otherwise it traverses until the correct spot is found.

if not head or node.val < head.val:
    node.next = head
    head = node
else:
    current = head
    while current.next and current.next.val < node.val:
        current = current.next
    node.next = current.next
    current.next = node
return head

List-to-Array Conversion for Large Inputs

When the list exceeds the moderate threshold, the algorithm collects all node values into a Python list, sorts it using the highly optimized native sort, and then writes the sorted values back into the original linked structure.

all = []
i = head
while i:
    all.append(i.val)
    i = i.next
all.sort()
i = head
for a in all:
    i.val = a
    i = i.next

Edge Cases Handled

The implementation explicitly checks for empty and single-node lists at the start of sortList. Returning None for an empty input and the original node for a single-element list avoids unnecessary processing.

if not head:  # size == 0
    return None
if not head.next:  # size == 1
    return head

During insertion, the code correctly handles insertion before the current head when the incoming node’s value is the smallest seen so far. The while-condition in insertOne ensures that traversal stops at the last node whose next value is still less than the node being inserted, thereby covering the case where the new node belongs at the tail of the sorted segment.

The bubble sort loop terminates gracefully when a full pass completes without any swaps, guaranteeing that the algorithm does not enter an infinite loop even if the list is already sorted.

Performance Optimizations Observed

The size-based dispatch avoids the quadratic cost of bubble sort on larger inputs by switching to insertion sort, which, while still O(n²) in the worst case, typically performs better on partially ordered data and benefits from pointer manipulation rather than value swapping.

For very large lists, the conversion to a native Python list leverages the highly tuned C implementation of list.sort, providing a substantial speed boost compared to any pure-Python linked-list sorting routine. By writing the sorted values back into the original nodes, the algorithm preserves the original node objects, which may be important for callers that retain external references.

The insertion routine minimizes allocations by reusing existing nodes and only adjusting next pointers, reducing overhead compared to approaches that create new node instances.

The bubble sort implementation swaps only the val fields, avoiding the cost of pointer updates and preserving node identity, which can be advantageous when external code holds references to specific node objects.

Overall, the code demonstrates a pragmatic blend of algorithmic choices tailored to input size, leveraging built-in language features where they offer the greatest efficiency.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of numbered building blocks that are all mixed up. To put them in order, you can use different strategies depending on how many blocks are in the line.

The first strategy is like a group of bubble dancers. The blocks keep checking who is next to them. If a block sees that the one to its right is smaller, they swap places and act like little bubbles popping and moving around. They keep doing this over and over until everything is perfectly lined up from smallest to largest.

The second strategy is like cleaning up a messy toy box. You take one block at a time from your pile and find the perfect spot for it in a new, growing line. You walk along the new line, looking for the right place to tuck the block in so all the numbers stay in the correct order. You keep doing this until every single block has a home.

Sometimes, if the line of blocks is very, very long, those two ways take a long time. When that happens, you can pick them all up, write down every single number on a piece of paper, sort the numbers on the paper super fast using a special trick, and then go back and change the numbers on the blocks to match your list. It is all about finding the cleverest way to make sure the numbers are in the right order without getting tired.

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 = 5 | μ = 5.30 | σ = 1.56

Complexity Analysis

not analyzed yet

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 C# Java Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
55 links | 38 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 5 medium
8 solutions   August 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