Given a linked list, determine if it has a cycle — meaning some node's next pointer points back to a previous node, creating an infinite loop.
Use Floyd's Tortoise and Hare algorithm: two pointers moving at different speeds. If there's a cycle, the fast pointer will eventually meet the slow pointer.
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Time: O(n), Space: O(1). This is much better than using a hash set (O(n) space).
# slow moves 1 step, fast moves 2 steps
# If no cycle: fast reaches None
# If cycle: they meet inside the cycle!
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
has_cycle(head1)
False
has_cycle(head2)
True