Linked ListMediumTwo pointers
Detect Cycle Visualizer
Slow moves one step, fast moves two. If they ever land on the same node, there is a loop.
In easy words
On a circular track a faster runner laps a slower one. If the list is a line, the fast runner hits the end.
Where this shows up
Cycle detection in graphs of nodes, hashmap memory leaks, and finding the loop start (Floyd phase 2).
Key facts
- Floyd - tortoise and hare, O(1) extra memory.
- Hash set - store seen nodes, O(n) memory.
- Meet - same node reference, not equal values.
- No cycle - fast becomes None.
What to remember
- Time - O(n).
- Space - O(1) for Floyd.
- Single node self-loop - they meet immediately after one move.
- Entry point - after meet, reset one pointer to head and walk together.
Theory
If a cycle exists, the faster pointer eventually laps the slower one inside the loop. This proves a cycle without storing every visited node.
Problem Statement
Given head of a linked list, return true if there is a cycle.
Example: 1 → 2 → 3 → 4 back to 2 has a cycle. 1 → 2 → 3 → None does not.
Approach
- Floyd's tortoise and hare. Slow moves one node, fast moves two.
- If they ever point to the same node, a cycle exists: the faster runner lapped the slower one on a loop.
- If fast hits None, the list is a straight line — no cycle.
- Why it works: inside a loop the gap shrinks by one each step, so they must meet. Extra memory is O(1).
Visualization and algorithm execution
Ready
1slow = fast = head
2while fast and fast.next:
3slow = slow.next
4fast = fast.next.next
5if slow == fast:
6return True
7return False
Trace log
slow = tortoise, fast = hare
?
Output:
Example program
1def hasCycle(head):
2slow = fast = head
3while fast and fast.next:
4slow = slow.next
5fast = fast.next.next
6if slow is fast: return True
7return False
1struct Node { int val; struct Node *next; };
2int hasCycle(struct Node *head) {
3struct Node *slow = head, *fast = head;
4while (fast && fast->next) {
5slow = slow->next;
6fast = fast->next->next;
7if (slow == fast) return 1;
8}
9return 0;
10}