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
Difficulty
and has an acceptance rate of about 66% (2+ million submissions).
Typical patterns to solve this problem:
- Linked List
- Recursion
- Stack
- 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 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.
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.
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 | 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++ |
Videos
Solved On The Same Day
- problem 263: Ugly Number
- problem 461: Hamming Distance
- problem 133: Clone Graph
- problem 142: Linked List Cycle II
- problem 264: Ugly Number II
- problem 313: Super Ugly Number
- problem 454: 4Sum II
- problem 477: Total Hamming Distance
- problem 10: Regular Expression Matching
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