876. Middle of the Linked List
Last updated
Was this helpful?
Last updated
Was this helpful?
🟩 Easy
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3.
Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
The number of nodes in the list is in the range [1, 100]
.
1 <= Node.val <= 100
My Solution
Optimal Solution (Two Pass)
This problem demonstrates two elegant approaches to find the middle node:
Fast & Slow Pointer (Your Solution):
Uses two pointers moving at different speeds
Fast moves twice as fast as slow
When fast reaches end, slow is at middle
Single pass, elegant solution
Two Pass Approach (Alternative):
First pass counts total nodes
Second pass moves to middle
More intuitive but less efficient
Good for learning linked lists
Time: O(n)
Single pass through list
Fast pointer moves n/2 times
Most efficient approach
Space: O(1)
Only two pointers
Constant extra space
No additional data structures
Time: O(n)
First pass: n steps to count
Second pass: n/2 steps to middle
Total: 1.5n steps
Space: O(1)
Only two variables
Counter and current pointer
Constant extra space
Mathematical Foundation:
Fast pointer moves at 2x speed
When fast reaches end
Slow has covered exactly half
Perfect for middle finding
Handling Edge Cases:
Works for odd and even lengths
Automatically finds second middle
No special case handling needed
Naturally handles single node
Fast & Slow Pattern Best For:
Finding middle elements
Cycle detection
Pattern finding in sequences
Distance-based problems
Two Pass Approach When:
Need total length anyway
Learning linked lists
Code readability priority
Teaching algorithms
Related Problems:
Linked List Cycle
Linked List Cycle II
Happy Number
Find the Duplicate Number
Key Techniques:
Two-pointer technique
Floyd's Cycle Finding
Runner technique
Distance calculations
Solution Highlights:
Single pass efficiency
No extra space needed
Works for all list sizes
Elegant mathematical property
Common Pitfalls:
Forgetting fast.Next check
Off-by-one in two-pass
Not handling edge cases
Wrong middle for even length
Testing Approach:
Empty list
Single node
Two nodes
Odd length list
Even length list
Follow-up Questions:
Handle circular lists?
Find first middle instead?
Return index instead of node?
Optimize for repeated calls?
Leetcode: