Floyd: slow + fast
pos is the index the tail links back to (−1 = acyclic). Slow walks one step, fast walks two. If they meet, there is a cycle.
On a cycle the fast pointer laps the slow one. On a line it hits the end first. No extra set of visited nodes.
Algorithm
- If
pos < 0or the list is empty, return false. - Advance slow by 1 and fast by 2 (wrapping the tail to
pos). - If they land on the same index, return true.
- Time
- O(n)
- Space
- O(1)
class Solution: def hasCycle(self, head: list[int], pos: int) -> bool: n = len(head) if n == 0 or pos < 0: return False def nxt(i: int) -> int: return pos if i == n - 1 else i + 1 slow = fast = 0 while True: slow = nxt(slow) fast = nxt(nxt(fast)) if slow == fast: return True