Problem 86

Abstract / Summary

Given the head of a linked list and a value x, rearrange the list so all nodes with values less than x come before nodes with values greater or equal to x.

Note

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

Python 0086.py

class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        if not head:
            return None

        small = []
        big   = []

        current = head
        while current:
            if current.val < x:
                small.append(current.val)
            else:
                big.append(current.val)
            current = current.next

        current = head
        while current:
            if small:
                current.val = small[0]
                del small[0]
            else:
                current.val = big[0]
                del big[0]
            current = current.next

        return head
27 lines | 697 bytes | submitted August 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (1+ million submissions).

Typical patterns to solve this problem:
  • Linked List
  • 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 method that rearranges a singly-linked list so that all nodes whose value is strictly less than a pivot x appear before nodes whose value is greater than or equal to x. The algorithm works in-place on the existing list nodes, preserving the original node objects while only mutating their stored values.

Key Steps

Early exit for an empty list

if not head:
    return None

The function first checks whether the input list is empty. If head is None, the routine returns None immediately, handling the edge case where there are no elements to process.

Partitioning values into two auxiliary containers

small = []
big   = []

current = head
while current:
    if current.val < x:
        small.append(current.val)
    else:
        big.append(current.val)
    current = current.next

A first traversal walks through the list node by node. Each node’s value is examined against the pivot x. Values that satisfy the “less than” condition are appended to the small list; all other values are appended to the big list. This step isolates the ordering information without altering the linked structure.

Re-injecting the partitioned values back into the original nodes

current = head
while current:
    if small:
        current.val = small[0]
        del small[0]
    else:
        current.val = big[0]
        del big[0]
    current = current.next

A second pass iterates over the original list again. As long as the small container still holds elements, the current node receives the first element from small. Once small is exhausted, the node receives values from big. The use of del small[0] (and similarly for big) removes the element that has just been consumed, ensuring that the next iteration sees the next value in order.

Returning the re-ordered list

return head

After the two passes, the linked list’s node values reflect the required partitioning, and the original head reference is returned.

Edge Cases Handled

When the input list is empty, the early return prevents any further processing.

If every node’s value is less than x, the big container remains empty; the second pass will consume all elements from small and never attempt to access big.

Conversely, if no node satisfies the “less than” condition, small stays empty from the start, and the second pass immediately begins pulling values from big.

A list consisting of a single node is also covered: the first traversal places the sole value into the appropriate container, and the second traversal writes it back to the same node, leaving the list unchanged apart from the logical partition.

Performance Optimizations Observed

The algorithm avoids allocating new linked-list nodes; it reuses the existing node objects and only creates two temporary Python lists to hold integer values. This reduces memory pressure associated with node creation and garbage collection.

Appending to Python lists (small.append and big.append) is an amortized constant-time operation, providing fast accumulation of values during the first traversal.

By performing exactly two linear passes over the list, the implementation ensures that each node is visited a predictable number of times, avoiding any nested loops or repeated scans.

The decision to mutate node values rather than relink nodes sidesteps the overhead of pointer manipulation, which can be beneficial in environments where object reference updates are more expensive than simple attribute assignments.

Overall, the code leverages straightforward list operations and a minimal number of traversals to achieve the partitioning goal while keeping auxiliary memory usage limited to the two value containers.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of toy trains, and each train has a number written on the side. Some of these numbers are small, and some are big, but they are all mixed up together. This code is like a helper that tidies up the line for you.

First, the helper walks down the line from the front to the end. Every time it sees a train with a small number, it puts a picture of that train into a special basket for small things. If the train has a big number, it puts a picture into a different basket for big things. Now the helper has two neat piles of numbers.

After the helper finishes looking at all the trains, it starts at the very beginning of the line again. It takes the first number from the small basket and puts it on the first train. Then it takes the next small number for the second train. It keeps doing this until the small basket is completely empty. Once there are no more small numbers left, the helper starts taking the numbers from the big basket and puts those onto the remaining trains. By the time it finishes, all the trains with small numbers are at the front of the line, and all the trains with big numbers are waiting at the back.

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 = 4 | μ = 4.30 | σ = 1.65

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 Java Rust JS C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
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++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
54 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Partition List - Linked List - Leetcode 86'
NeetCode 8 mins
Partition List - Linked List - Leetcode 86
YouTube video 'Partition List | Live Coding with Explanation | Leetcode - 86'
Algorithms Made Easy 7 mins
Partition List | Live Coding with Explanation | Leetcode - 86
YouTube video '[Java] Leetcode 86. Partition List [LinkedList #8]'
Eric Programming 6 mins
[Java] Leetcode 86. Partition List [LinkedList #8]
YouTube video 'partition list | partition list leetcode | leetcode 86 | linked list'
Naresh Gupta 8 mins
partition list | partition list leetcode | leetcode 86 | linked list
YouTube video 'Leetcode 86: Partition List'
Algorithms Casts 10 mins
Leetcode 86: Partition List
YouTube video 'Partition List | Leetcode 86 | Live Coding session'
Coding Decoded 12 mins
Partition List | Leetcode 86 | Live Coding session
YouTube video 'Partition List  || Linked List 11 || Placement Preparation Series || LeetCode 86|| Medium ||'
Bro Coders 10 mins
Partition List || Linked List 11 || Placement Preparation Series || LeetCode 86|| Medium ||
YouTube video '86. Partition List | Java | Leetcode | Linked List | DSA'
Coding with Tamilarasan 13 mins
86. Partition List | Java | Leetcode | Linked List | DSA
YouTube video '86 || Partition List II || C++ || Leetcode Daily Challenge'
CodeFreaks 7 mins
86 || Partition List II || C++ || Leetcode Daily Challenge
YouTube video 'Daily Leetcode #843: Jul 22, 2022 - 86. Partition List'
Programming Live with Larry 7 mins
Daily Leetcode #843: Jul 22, 2022 - 86. Partition List
YouTube video 'Leetcode 86: Partition List in Telugu | Two Pointers Approach | Python DSA | srkcodes'
Srk Codes 11 mins
Leetcode 86: Partition List in Telugu | Two Pointers Approach | Python DSA | srkcodes
YouTube video 'Leetcode 86 - Partition List (JAVA, Solution Explain!)'
LC Bear 7 mins
Leetcode 86 - Partition List (JAVA, Solution Explain!)
YouTube video '86. Partition List | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 21 mins
86. Partition List | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'Daily Leetcode #1232: Aug 15, 2023 - 86. Partition List'
Programming Live with Larry 11 mins
Daily Leetcode #1232: Aug 15, 2023 - 86. Partition List
YouTube video 'Can You Partition a List? (LeetCode 86: Partition List)'
Code With Zi 11 mins
Can You Partition a List? (LeetCode 86: Partition List)
YouTube video 'Daily Leetcode #379: Apr 14, 2021 - 86. Partition List'
Programming Live with Larry 9 mins
Daily Leetcode #379: Apr 14, 2021 - 86. Partition List
YouTube video 'Leetcode 86. Partition List - July Daily Challenge'
Algorithms Casts 13 mins
Leetcode 86. Partition List - July Daily Challenge
YouTube video 'Partition List - LeetCode 86 - Python'
Alpha-Code 14 mins
Partition List - LeetCode 86 - Python
YouTube video '86. Partition List | Leetcode | Python'
Abdullah Arshed 4 mins
86. Partition List | Leetcode | Python
YouTube video 'Leetcode [086] Partition List'
SDE Skills 8 mins
Leetcode [086] Partition List
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 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