Problem 328

Abstract / Summary

Rearrange a linked list so that all nodes at odd positions come first followed by all nodes at even positions.

Note

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

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
26 lines | 729 bytes | submitted September 12, 2023 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Linked List
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 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.

written by openai gpt

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.

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 = 6 | μ = 5.74 | σ = 1.55

Complexity Analysis

Time: linear
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 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++
47 links | 33 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

26 solutions   September 12, 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