Graph Theory37 sections · 1633 units
Open in Course

Linked List Cycle II - Implementation

(Floyd's algorithm in code)

Here is the solution:

function detect_cycle(head)
    slow := head
    fast := head
    while fast and fast.next
        slow := slow.next
        fast := fast.next.next
        if slow = fast then
            ptr := head
            while ptr != slow
                ptr := ptr.next
                slow := slow.next
                return ptr
    return null

Time: O(n)O(n) where nn is the number of nodes. Space: O(1)O(1) since you only use two pointers. No visited set needed. The algorithm is simple but powerful.