Problem 876

Abstract / Summary

Find the middle node in a singly linked list.

Note

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

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
8 lines | 266 bytes | submitted October 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (3+ million submissions).

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

written by openai gpt

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.

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 = 9 | μ = 8.37 | σ = 1.31

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 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++
48 links | 31 authors | 13 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

2 easy
3 solutions   October 21, 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