sagelearnai

Middle of the Linked List

Difficulty: Easy · Pattern: Fast & Slow Pointers · LeetCode #876

Return the middle node of a non-empty singly linked list. If there are two middle nodes (even length), return the second one. (The tests show the list from the returned node onward.)

Examples

text
1 → 2 → 3 → 4 → 5        →  3 → 4 → 5
1 → 2 → 3 → 4 → 5 → 6    →  4 → 5 → 6

Hints

  1. Counting the length then walking half is two passes. Can you do it in one?
  2. When a pointer moving twice as fast reaches the end, where is the slow one?

Approach

Start slow and fast at the head. While fast and fast.next exist, move slow one step and fast two. When fast can't move further, slow is at the middle. For even lengths, this loop condition naturally lands on the second middle.

Complexity

Time: O(n). Space: O(1).

Python solution
def middleNode(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow
JavaScript solution
function middleNode(head) {
  let slow = head, fast = head;
  while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
  return slow;
}