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
Difficulty
and has an acceptance rate of about 62% (1+ million submissions).
Typical patterns to solve this problem:
- Linked List
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
Extra
- 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