Python 0876.py
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next
fast = fast.next
return slow
Difficulty
and has an acceptance rate of about 82% (3+ 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 finds the middle node of a singly-linked list using a two-pointer technique. It creates two references, slow and fast, both initially pointing at the head of the list. By advancing fast twice as quickly as slow, the algorithm guarantees that when fast reaches the end, slow will be positioned at the middle. The method returns the node referenced by slow, which represents the required middle element.
Key Steps
Initialization
Both pointers are set to the same starting node. This ensures that the traversal begins from the head and that the relative distance between the pointers is zero at the outset.
slow = fast = head
Traversal Loop
The core of the algorithm is a loop that continues while fast and fast.next are not None. Inside the loop, slow moves one step forward, while fast moves two steps. The two separate assignments to fast make the two-step advancement explicit.
while fast and fast.next:
slow = slow.next
fast = fast.next
fast = fast.next
Return Statement
After the loop terminates, slow points to the middle node. The method returns this reference directly.
return slow
Edge Cases Handled
When the input list is empty (head is None), the initial assignment sets both pointers to None. The loop condition fails immediately because fast is None, and the method returns None, correctly indicating that there is no middle node.
If the list contains a single node, slow and fast both reference that node. The loop condition fails because fast.next is None. The method returns the sole node, which is trivially the middle.
For lists with an even number of nodes, the algorithm returns the second of the two central nodes. This behavior emerges naturally from the loop condition: when fast reaches the end after an even number of steps, slow has advanced exactly half the length, landing on the later middle node.
Performance Optimizations
The solution operates in a single pass over the list, avoiding any need for auxiliary data structures such as arrays or stacks. By reusing the two pointer variables throughout the traversal, it maintains a constant amount of extra memory regardless of list size. The explicit two-step advancement of fast eliminates the need for additional arithmetic or modulo operations, keeping the inner loop body minimal and cache-friendly. This streamlined approach yields efficient execution even for very long linked lists.
ELI5 - Simplified Explanation
Imagine there is a train made of many little carriages all linked together one after another. This code helps find the exact middle carriage of that long train. To do this, picture two friends running along the top of the train at the same time. The first friend takes one step forward to the very next carriage. At the same time, the second friend is much faster and jumps ahead two carriages at once. Because the second friend is hopping along faster, they will reach the very end of the train while the first friend is only halfway through. When the fast friend finishes jumping off the end, the first friend is standing right in the middle where they belong. The code just keeps these two friends moving along until the fast one reaches the end, and then it stops to show where the slow friend is standing.
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 | C | Rust | PHP | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | Python | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C | |||||||||||||
| lkwq007 | Python | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| zfang399 | C++ | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C, C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | Python | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C | |||||||||||||
| lkwq007 | Python | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
Solved On The Same Day
- problem 977: Squares of a Sorted Array
- problem 1018: Binary Prefix Divisible By 5
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