Linked List Cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. A cycle exists if some node can be reached again by continuously following the `next` pointer. **Core Insight:** Floyd's Cycle Detection Algorithm (the "tortoise and hare"). Use two pointers: `slow` moves one step at a time, `fast` moves two steps. If there is a cycle, `fast` will eventually lap `slow` and they will meet at the same node. If there is no cycle, `fast` will reach `null` first. **Algorithm:** Initialize both `slow` and `fast` at `head`. Loop while `fast` and `fast.next` are not null: advance `slow` by 1, `fast` by 2. If `slow == fast` at any point, return `true`. Return `false` when the loop exits. **Why they meet:** In a cycle of length L, the gap between fast and slow decreases by 1 each step, so they must meet within L steps of entering the cycle. **Complexity:** Time O(n) — at most n steps before meeting or reaching null. Space O(1) — only two pointer variables.
Constraints
- •
The number of nodes is in the range [0, 10⁴]
def hasCycle(head) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False