Middle of the Linked List
Middle of the Linked List is a easy linked list problem solved with the slow fast pointers pattern.
The best approach, optimal (slow and fast pointers), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, from two passes (count) up.
Problem
Return the middle node of a linked list. If there are two middle nodes, return the second one.
Examples
Example 1
- Input
head = [1, 2, 3, 4, 5]- Output
[3, 4, 5]
Example 2
- Input
head = [1, 2, 3, 4]- Output
[3, 4]- Why
- With two middles, return the second one.
Constraints
- The list has
1to100nodes.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Two passes (count) | O(n) | O(1) |
| Optimal (slow and fast pointers) | O(n) | O(1) |
1Two passes (count)
O(n)O(1)Count the nodes, then walk n / 2 steps.
- Count n; walk n / 2 steps from head.
class Solution {
public ListNode middleNode(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
ListNode mid = head;
for (int i = 0; i < n / 2; i++) mid = mid.next;
return mid;
}
}2Optimal (slow and fast pointers)
O(n)O(1)Move slow by one and fast by two. When fast runs off the end, slow is at the middle (the second middle for even lengths).
- slow = fast = head.
- While fast and fast.next exist: slow = slow.next; fast = fast.next.next.
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}Edge cases to test
- Single node
- Even length (second middle)
Hints
Hint 1
If one pointer moves twice as fast as another, where is the slow one when the fast one finishes?
FAQ
What is the best time complexity for Middle of the Linked List?
Optimal (slow and fast pointers) runs in O(n) time and O(1) extra space.
Which pattern does Middle of the Linked List use?
It is a linked list problem that uses the slow fast pointers pattern. Other problems with the same pattern: Linked List Cycle, Linked List Cycle II.
Is there a brute force solution for Middle of the Linked List?
Yes. Two passes (count) takes O(n) time and O(1) space. Count the nodes, then walk n / 2 steps.
Which edge cases should I test for Middle of the Linked List?
Single node; Even length (second middle).