Python 0328.py
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# no change if length <= 2
if not head or not head.next or not head.next.next:
return head
# find end of list
last = head
while last.next:
last = last.next
stop = head.next
scan = head
while True:
# cut out even index
even = scan.next
scan.next = scan.next.next
scan = scan.next
# append to end
even.next = None
last.next = even
last = last.next
if scan == stop or scan.next == stop:
return head
Difficulty
and has an acceptance rate of about 63% (2+ million submissions).
Typical patterns to solve this problem:
- Linked List
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 rearranges a singly-linked list so that all nodes positioned at odd indices appear before those at even indices, preserving the original relative order within each group. The method returns the head of the modified list, handling short lists early and then performing an in-place transformation that avoids additional data structures.
Core Logic
The algorithm begins by checking whether the list contains fewer than three nodes. In such cases the original list is returned unchanged because no reordering is required.
if not head or not head.next or not head.next.next:
return head
Next, the code locates the current tail of the list. This tail will serve as the insertion point for nodes that are removed from their original even positions.
last = head
while last.next:
last = last.next
Two pointers, stop and scan, are then initialized. stop marks the node that originally follows the headโs immediate neighbor, acting as a sentinel that signals when the reordering loop should terminate. scan starts at the head and moves forward as odd-indexed nodes are retained.
stop = head.next
scan = head
The main loop repeatedly extracts the node immediately after scan (the even-indexed node), relinks the odd chain, and appends the extracted node to the end of the list. The extraction step cuts the even node out of its original position:
even = scan.next
scan.next = scan.next.next
scan = scan.next
Appending the extracted node to the tail involves clearing its next reference, linking it after last, and then advancing last to point to the newly added node:
even.next = None
last.next = even
last = last.next
The loop terminates when scan reaches the sentinel stop or when the node following scan is the sentinel, ensuring that all original even-indexed nodes have been moved to the tail.
if scan == stop or scan.next == stop:
return head
Edge Cases Handled
The early return condition covers three distinct edge situations: an empty list, a single-node list, and a two-node list. In each of these scenarios the list length is insufficient to require any rearrangement, and the function exits immediately, preserving the original structure.
The termination condition inside the loop uses the stop sentinel to detect when the scanning pointer has progressed to the region that originally contained the first even node. This prevents the algorithm from entering an infinite loop when the list length is odd, as the sentinel will be encountered after the final odd node has been processed. It also correctly handles the case where the list length is even, because the condition scan.next == stop captures the moment just before the last even node would be processed again.
Performance Optimizations
The implementation achieves its goal with a single traversal to locate the original tail and a second traversal that processes each node exactly once. By reusing the existing nodes and adjusting pointers in place, the algorithm avoids allocating auxiliary containers or creating new list nodes, which reduces memory pressure.
Appending nodes to the tail is performed by maintaining a direct reference (last) to the current end of the list. This eliminates the need to walk from the head to the tail for each insertion, ensuring that each append operation executes in constant time.
The use of a sentinel (stop) eliminates the need for counting the total number of nodes or maintaining separate length variables. This approach simplifies the loop condition and avoids extra arithmetic, contributing to a leaner runtime profile.
Overall, the code delivers an in-place reordering with minimal overhead, leveraging pointer manipulation to achieve the desired odd-even separation efficiently.
ELI5 - Simplified Explanation
Imagine a long train where every car is linked to the one behind it. Some cars have odd numbers and some have even numbers, and they are currently all mixed together. The goal of this code is to take all the even-numbered cars and move them to the back of the train so that the odd ones are all at the front and the even ones follow behind.
First, the code checks to see if the train is too short to change. If there are only one or two cars, everything is already as it should be, so the code leaves it alone.
Next, the code walks to the very end of the train to find the last car. Knowing where the end is helps when it comes time to park the even cars in the back later.
Then, the code starts a loop to move the cars. It looks at a car, then jumps over the next one to pick up the even-numbered car. It unhooks that even car from the middle of the train and moves it all the way to the back, attaching it right after the car that was previously at the end. After the even car is moved, the train cars in front of the gap are connected together so there is no empty space left behind.
The code keeps doing this over and over again, jumping, moving, and reattaching, until all the even cars have been gathered from the front and placed in a row at the back. Once all the even cars have been moved to their new spot at the end of the line, the job is finished.
Code Quality
Complexity Analysis
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
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 | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| vthwang | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 725: Split Linked List in Parts
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
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