DSA Patterns (Multi-Lang)•Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)
Linked List Cycle (Floyd’s Tortoise and Hare).
In Simple Words:
Slow pointer moves 1 step, fast pointer moves 2 steps. If there is a cycle, fast will eventually lap slow and slow === fast. If fast hits null, no cycle exists.
- Time: $O(N)$ | Space: $O(1)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef hasCycle(head: ListNode | None) -> bool:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False