Problem 147

Abstract / Summary

Sort a linked list by rearranging nodes in ascending order using a method similar to manual sorting.

Note

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

Python 0147.py

class Solution:
    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 insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # taken from problem 148 (which I solved first)

        # 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
25 lines | 827 bytes | submitted August 16, 2023 | GitHub   9% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (800k+ submissions).

Typical patterns to solve this problem:
  • Linked List
  • Sorting
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 sorts a singly-linked list using the insertion-sort technique. It consists of two methods: a helper that inserts a single node into an already sorted sub-list, and the main routine that repeatedly extracts nodes from the original list and places them into the growing sorted portion. The algorithm works entirely by rewiring the next pointers, leaving the node values untouched.

Key Functions

insertOne

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

The helper receives the head of a sorted list and a solitary node that must be placed in order. It first checks whether the sorted list is empty or whether the new node belongs at the very front. In those cases it links the new node before the existing head and returns the updated head reference. Otherwise it walks forward with a current pointer until it finds the correct insertion point-specifically the last node whose successor has a value smaller than the node to insert. At that moment the method splices the node between current and current.next. The function finally returns the (potentially unchanged) head of the sorted segment.

insertionSortList

def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
    # taken from problem 148 (which I solved first)

    # 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

The main routine initializes two pointers: done for the sorted portion (initially empty) and todo for the remainder of the original list. While there are nodes left to process, it temporarily stores the successor of todo, inserts the current node into done via insertOne, and then advances todo to the saved successor. When the loop terminates, done points to the fully sorted list, which is returned to the caller.

Edge Cases Handled

The code explicitly addresses the situation where the input list is empty; the while todo: loop simply never executes, and the method returns None. In insertOne, the condition if not head or node.val < head.val: covers both an empty sorted list and the case where the new node is the smallest element, ensuring correct placement at the head without additional checks. The traversal loop while current.next and current.next.val < node.val: naturally stops at the end of the list, so inserting a node larger than all existing elements results in appending it to the tail. By preserving the original next reference before insertion, the algorithm avoids losing the remainder of the unsorted segment.

Performance Optimizations

The implementation achieves efficiency by reusing existing node objects rather than creating new ones or swapping values. Each node is moved exactly once from the unsorted region to the sorted region, and the pointer adjustments are performed in constant time per insertion. The helper function stops its traversal as soon as it encounters a node with a value not less than the one being inserted, preventing unnecessary scans of the already sorted tail. Moreover, the main loop maintains a simple reference to the next node (next = todo.next) before any modifications, eliminating the need for additional data structures or auxiliary storage. This in-place manipulation of links minimizes memory overhead and keeps the runtime overhead low.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of cards that have numbers written on them, but they are all jumbled up and out of order. This code acts like a very organized robot whose job is to sort those cards from smallest to biggest.

The robot starts with an empty space on the table where it will put the sorted cards. It looks at the jumbled line one card at a time. Every time the robot picks up a card from the pile, it walks along the space on the table to find the perfect spot for it.

The robot checks the numbers already on the table and slides the new card right into place so that everything stays in the correct order. If the card is smaller than the very first one, it gets placed at the front. Otherwise, the robot walks past the cards that are already smaller until it finds the place where the new one fits.

It keeps doing this over and over again, picking up one card after another from the messy pile and putting it into the finished line. Once there are no more cards left in the messy pile, all the cards are lined up perfectly on the table from smallest to biggest. The cards are still connected like a string of beads, and the robot just moves the connections around until the order is beautiful.

written by google gemini

Code Quality

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

Complexity Analysis

Time: polynomial
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 Python JS Java Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca Go, Java, JavaScript, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
46 links | 33 authors | 10 languages

Videos

13 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