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

Keep a gap of k, and the trailing pointer stops k from the end

A fixed gap between two pointers finds a position counted from the end.

def kth_from_end(head, k):
    lead = head
    for _ in range(k):
        if lead is None:
            # fewer than k nodes
            return None
        lead = lead.next
    trail = head
    while lead is not None:
        lead, trail = lead.next, trail.next
    return trail


nums = linked([1, 2, 3, 4, 5])
print([kth_from_end(nums, k).val for k in (1, 2, 5)], kth_from_end(nums, 6))
Predict

On 1 to 5, what are the 1st, 2nd and 5th from the end, and the 6th?

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