14/39
Part 3 of 7 · Reversing and two speedsLearn and do

Two pointers at two speeds

A linked list has no index, but two pointers that move at different speeds can still answer questions about positions in one walk, with O(1) memory.

def middle(head):
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow, fast = slow.next, fast.next.next
    return slow


print(middle(linked([1, 2, 3, 4, 5])).val, middle(linked([1, 2, 3, 4, 5, 6])).val)
Predict

fast moves two nodes for each one slow moves. Where does slow stop on 1 to 5, and on 1 to 6?

Pick one to see what it prints.
Pick an answer above to see the rest