Problem 143

Abstract / Summary

Given a linked list, reorder it so nodes appear in the order first to last, then last to second, and so on.

Note

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

Python 0143.py

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        all = []
        current = head
        while current:
            all.append(current)
            current = current.next

        i = 0
        j = len(all) - 1
        while i < j:
            all[i].next = all[j]
            i += 1
            if i < j:
                all[j].next = all[i]
                j -= 1

        all[i].next = None

        return head
20 lines | 471 bytes | submitted August 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Linked List
  • Recursion
  • Stack
  • 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 implementation reorders a singly-linked list so that nodes appear in the pattern first, last, second, second-last, and so on. The method receives the head of the list, rearranges the next pointers in-place, and returns the original head reference. The algorithm proceeds in three conceptual phases: collection of node references, two-pointer weaving of the list, and termination of the final node.

Collection of Nodes

The first loop walks the original list from the head to the tail, appending each node object to a Python list named all. This creates an indexed snapshot of the list structure, enabling direct random access to any node by its position.

all = []
current = head
while current:
    all.append(current)
    current = current.next

By storing the nodes, the algorithm avoids repeated traversal when pairing elements from opposite ends of the list.

Two-Pointer Weaving

After the collection phase, two indices i and j are initialized to point at the start and end of the all array. A while loop runs while i is less than j. Inside the loop the node at position i is linked to the node at position j. The start index is then advanced. If the indices have not crossed, the node at position j is linked back to the new start node, and the end index is decremented. This alternating linking produces the required reorder without allocating new nodes.

i = 0
j = len(all) - 1
while i < j:
    all[i].next = all[j]
    i += 1
    if i < j:
        all[j].next = all[i]
        j -= 1

The conditional check after incrementing i guarantees that the middle element in an odd-length list is not linked twice, preserving correct ordering.

Termination of the List

When the weaving loop finishes, i points to the middle node (or the last node in an even-length list). Setting its next reference to None terminates the reordered list cleanly, preventing any stray links that could create cycles.

all[i].next = None

Finally, the original head reference is returned, although the method’s contract specifies an in-place modification and does not require a return value.

Edge Cases Handled

When the input list is empty (head is None), the initial collection loop never executes, leaving all empty. The subsequent index calculations produce j = -1, and the weaving loop condition i < j fails immediately. The termination step accesses all[i] only after confirming that i is a valid index, so no exception occurs.

For a single-node list, the collection array contains one element. The indices start as i = 0 and j = 0; the weaving loop does not run because i is not less than j. The termination step sets the sole node’s next to None, which is already the case, leaving the list unchanged.

A two-node list yields i = 0 and j = 1. The first iteration links the first node to the second, increments i to 1, and the inner conditional fails because i is no longer less than j. The termination step then sets the second node’s next to None, correctly preserving the original order, which matches the required reordered pattern for two elements.

Odd-length lists (e.g., five nodes) result in the middle node becoming the final i after the weaving loop. The conditional guard prevents linking the middle node to itself, and the termination step cleanly ends the list after the middle node.

Even-length lists (e.g., six nodes) finish with i pointing to the first node of the second half after the last pairing, and the termination step cuts off any residual link beyond the reordered sequence.

Performance Optimizations

The primary optimization is the use of a contiguous array to hold node references. This enables constant-time access to both ends of the list, eliminating the need for repeated traversal that would be required if the algorithm attempted to locate the last node on each iteration.

All pointer adjustments are performed directly on existing node objects; no auxiliary nodes are allocated, and the original list nodes are reused throughout. This in-place modification reduces memory pressure to the size of the reference array, which is proportional to the number of nodes but avoids additional heap allocations for new list elements.

The algorithm performs a single linear pass to collect nodes, followed by a second linear pass to rewire pointers. By separating collection from rewiring, the code avoids the overhead of nested loops or recursive calls, keeping the execution flow straightforward and cache-friendly.

The conditional check inside the weaving loop (if i < j) ensures that the inner linking step is skipped when the indices meet, preventing unnecessary pointer assignments and preserving correctness without extra branching.

Overall, the design balances simplicity with efficient use of data structures, achieving the reorder operation with minimal overhead while maintaining clear and deterministic control flow.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a train made of many little cars all linked together in a long line. This code is like a game to shuffle the cars so the order gets mixed up in a special way.

First, the code walks down the whole train from the front to the back, looking at every single car. It keeps a list of all the cars so it knows exactly where everyone is hiding.

Then, the game starts. The code picks the very first car and tells it to hold hands with the very last car. After that, it picks the last car and tells it to hold hands with the second car. It keeps going back and forth, jumping from the front to the back and linking the cars together in this new sequence, like a zipper closing up tight.

When the code gets to the middle and there are no more cars to link, it tells the last one to stop reaching out so the train has a proper ending. It is a way to reorganize the line so it looks totally different than it did when it started.

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.89 | σ = 1.13

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 Rust C# JS Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
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++
martianoff Scala
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 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
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
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++
martianoff Scala
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
59 links | 42 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Reorder List | Leetcode 143 | Linked List'
Ayushi Sharma 16 mins
Reorder List | Leetcode 143 | Linked List
YouTube video 'Reorder List | 3 Approaches | Leetcode 143 | codestorywithMIK'
codestorywithMIK 40 mins
Reorder List | 3 Approaches | Leetcode 143 | codestorywithMIK
YouTube video 'Reorder List | LeetCode 143 | C++, Java, Python'
Knowledge Center 25 mins
Reorder List | LeetCode 143 | C++, Java, Python
YouTube video 'Reorder List | Day 20 | [ August LeetCoding Challenge ] [ Leetcode #143 ] [ 2020 ]'
Algorithms Made Easy 5 mins
Reorder List | Day 20 | [ August LeetCoding Challenge ] [ Leetcode #143 ] [ 2020 ]
YouTube video 'Reorder List | Leet code 143 | Theory explained + Python code'
Sai Anish Malla 10 mins
Reorder List | Leet code 143 | Theory explained + Python code
YouTube video '[Java] Leetcode 143. Reorder List [Fast & Slow Pointers #5]'
Eric Programming 11 mins
[Java] Leetcode 143. Reorder List [Fast & Slow Pointers #5]
YouTube video 'reorder list | reorder list leetcode | leetcode 143 | 2 solutions | with stack | reverse second half'
Naresh Gupta 13 mins
reorder list | reorder list leetcode | leetcode 143 | 2 solutions | with stack | reverse second half
YouTube video 'REORDER LIST | LEETCODE 143 | PYTHON  SOLUTION'
Cracking FAANG 14 mins
REORDER LIST | LEETCODE 143 | PYTHON SOLUTION
YouTube video 'Leetcode | 143. Reorder List | Medium | Java Solution'
Developer Docs 6 mins
Leetcode | 143. Reorder List | Medium | Java Solution
YouTube video 'Reorder List | Leetcode 143 | Live coding session 🔥🔥🔥 | Linear Time Complexity'
Coding Decoded 4 mins
Reorder List | Leetcode 143 | Live coding session 🔥🔥🔥 | Linear Time Complexity
YouTube video 'Reorder List | Leetcode August Challenge | Leetcode medium 143'
Coding Decoded 11 mins
Reorder List | Leetcode August Challenge | Leetcode medium 143
YouTube video '143. Reorder List  | March | Java | C++'
Mayur Programming Club 24 mins
143. Reorder List | March | Java | C++
YouTube video 'Leetcode 143 - Reorder List (JAVA Solution Explained!)'
LC Bear 8 mins
Leetcode 143 - Reorder List (JAVA Solution Explained!)
YouTube video 'Reorder List - LeetCode #143 - C++'
Sean Chuah 6 mins
Reorder List - LeetCode #143 - C++
YouTube video 'Daily Leetcode #631: Dec 22, 2021 - 143. Reorder List'
Programming Live with Larry 25 mins
Daily Leetcode #631: Dec 22, 2021 - 143. Reorder List
YouTube video 'Reorder List | LeetCode 143 | Coders Camp'
Coders Camp 13 mins
Reorder List | LeetCode 143 | Coders Camp
YouTube video 'Daily Leetcode #1453: Mar 23, 2024 - 143. Reorder List'
Programming Live with Larry 14 mins
Daily Leetcode #1453: Mar 23, 2024 - 143. Reorder List
YouTube video 'Daily Leetcode #142: Aug 20, 2020 - 143. Reorder List'
Programming Live with Larry 25 mins
Daily Leetcode #142: Aug 20, 2020 - 143. Reorder List
YouTube video '37. Leetcode 143. Reorder List : Javascript'
Web Fusion with Bharadwaj 13 mins
37. Leetcode 143. Reorder List : Javascript
YouTube video 'LeetCode 143 - Reorder List - Java'
Alpha-Code 15 mins
LeetCode 143 - Reorder List - Java
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 6 medium 1 hard
10 solutions   August 19, 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