Stage 1 · Code
Two Pointers & Sliding Window
Fast & Slow Pointers
Two pointers moving at different speeds — detects cycles and finds midpoints in O(n) time and O(1) space.
The Pattern
Slow moves 1 step, fast moves 2 steps. If there is a cycle, fast will lap slow — they must meet. If there is no cycle, fast exits the list. Finding the cycle start requires a second phase: reset one pointer to head and advance both at speed 1.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
def find_cycle_start(head: ListNode) -> ListNode | None:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# Phase 2: reset one pointer to head
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return NoneMathematical proof: if cycle length is C and cycle start is at position k, when slow enters the cycle, fast is k%C steps ahead. They meet in C-k%C steps. Resetting to head then advances both at speed 1, meeting exactly at the cycle start.
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.