Middle of the Linked List
Problem
Given the head of a singly linked list, return its middle node. If there are two middle nodes, return the second one.
Example 1
- Input
head = [1, 2, 3, 4, 5]- Output
[3, 4, 5]- Why
- Node 3 is the middle.
Example 2
- Input
head = [1, 2, 3, 4, 5, 6]- Output
[4, 5, 6]- Why
- Two middles (3 and 4): return the second.
Constraints
- 1 ≤ number of nodes ≤ 100
Explanation
If one pointer moves twice as fast as another, the slow one is halfway when the fast one reaches the end.
Approach 1 · Naive
Count, then walk half
- Time O(n), two passes
- Space O(1)
Count the nodes in one pass, then walk count / 2 steps from the head.
- Count the nodes
n. - Walk
n / 2steps fromheadand return that node.
class Solution {
public ListNode middleNode(ListNode head) {
int n = 0;
for (ListNode node = head; node != null; node = node.next) {
n++;
}
ListNode node = head;
for (int i = 0; i < n / 2; i++) {
node = node.next;
}
return node;
}
}class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
n, node = 0, head
while node:
n += 1
node = node.next
node = head
for _ in range(n // 2):
node = node.next
return nodeApproach 2 · Optimal
Slow and fast pointers
- Time O(n), one pass
- Space O(1)
Move slow one step and fast two steps until fast cannot move further.
- Set
slow = fast = head. - While
fastandfast.nextexist, moveslowonce andfasttwice. - Return
slow.
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowComplexity compared
| Approach | Time | Space |
|---|---|---|
| Naive Count, then walk half | O(n), two passes | O(1) |
| Optimal Slow and fast pointers | O(n), one pass | O(1) |
Key takeaways
- To get the first middle instead, loop while
fast.nextandfast.next.nextexist.
Your notes
Saved in this browser as you type.
Solved it on your own?
Mark it done to track your progress, or star it to come back before an interview.