← Linked Lists

Drill #14 — Find middle node

Easy Slow/Fast Linked Lists

In plain English: Find the middle element of a linked list in one pass without knowing its length.

When the fast pointer reaches the end at 2x speed, the slow pointer is exactly at the midpoint — one pass, no length needed.

Prompt

Find the middle node of a linked list.

Try to write it from scratch before scrolling down.

Solution

def find_middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    # fast at end = slow at middle
    return slow

# Test: 1->2->3->4->5 => node(3)
O(n) time · O(1) space

Related Micro Drills

← Drill #13 Drill #15 →