Problem Statement
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.
Intuition
If a cycle exists, a fast pointer (moving two steps at a time) will eventually lap a slow pointer (moving one step). If there's no cycle, the fast pointer reaches the end.
This is known as Floyd's cycle detection algorithm, or the tortoise and hare algorithm.
Approach
- Initialize two pointers,
slowandfast, both at head. - Move
slowone step andfasttwo steps per iteration. - If
fastorfast.nextis null, return false (no cycle). - If
slow === fast, return true (cycle detected).
Solution
TypeScript
function hasCycle(head: ListNode | null): boolean {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Fast pointer traverses at most 2n steps | |
| Space | Only two pointers used |