Middle of the Linked List - Problem
You're given the head of a singly linked list, and your task is to find and return the middle node of the list.
Here's the catch: if the linked list has an even number of nodes (meaning there are two potential middle nodes), you should return the second middle node.
Example: In a list with nodes [1,2,3,4,5], the middle node is 3. In a list with nodes [1,2,3,4,5,6], there are two middle nodes (3 and 4), so return node 4.
This is a classic problem that tests your understanding of linked list traversal and the elegant two-pointer technique!
Input & Output
example_1.py โ Odd Length List
$
Input:
[1,2,3,4,5]
โบ
Output:
[3,4,5]
๐ก Note:
The middle node is the 3rd node in the list (value 3). Return the node and all subsequent nodes.
example_2.py โ Even Length List
$
Input:
[1,2,3,4,5,6]
โบ
Output:
[4,5,6]
๐ก Note:
There are two middle nodes (3 and 4). Since we need the second middle node, return node 4 and all subsequent nodes.
example_3.py โ Single Node
$
Input:
[1]
โบ
Output:
[1]
๐ก Note:
With only one node, that node is both the head and the middle. Return the single node.
Visualization
Tap to expand
Understanding the Visualization
1
Start Together
Both slow (๐ข) and fast (๐ฐ) pointers begin at the head node
2
Different Speeds
In each step: slow moves 1 position, fast moves 2 positions
3
Fast Reaches End
When fast pointer reaches the end or goes beyond, slow is at middle
4
Perfect Positioning
The slow pointer is guaranteed to be at the middle (or second middle for even length)
Key Takeaway
๐ฏ Key Insight: The two-pointer technique guarantees that when the fast pointer (moving 2x speed) reaches the end, the slow pointer (moving 1x speed) will be exactly at the middle position. This works for both odd and even length lists!
Time & Space Complexity
Time Complexity
O(n)
Two traversals of the linked list: O(n) + O(n/2) = O(n)
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to store count and current position
โ Linear Space
Constraints
- The number of nodes in the list is in the range [1, 100]
- 1 โค Node.val โค 100
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code