Detect Cycle in Linked List Floyd's Algorithm in DSA Python - Time & Space Complexity
We want to understand how the time needed to detect a cycle in a linked list grows as the list gets longer.
Specifically, how many steps does Floyd's Algorithm take to find a cycle or confirm there is none?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, val):
self.val = val
self.next = None
def has_cycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
This code uses two pointers moving at different speeds to detect if a linked list has a cycle.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that moves the slow pointer one step and the fast pointer two steps each time.
- How many times: At most, the loop runs once per node until the fast pointer reaches the end or the pointers meet.
As the linked list grows, the number of steps grows roughly in a straight line with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase directly with the number of nodes, so doubling nodes roughly doubles steps.
Time Complexity: O(n)
This means the time to detect a cycle grows linearly with the size of the linked list.
[X] Wrong: "Because the fast pointer moves twice as fast, the algorithm runs in constant time O(1)."
[OK] Correct: Even though the fast pointer moves faster, it still needs to traverse nodes, so the total steps depend on the list size.
Understanding this linear time complexity helps you explain why Floyd's Algorithm is efficient and preferred for cycle detection in interviews.
"What if we used a hash set to store visited nodes instead? How would the time complexity change?"
Practice
Solution
Step 1: Understand Floyd's algorithm concept
It uses two pointers, one moving fast (two steps) and one slow (one step).Step 2: Detect cycle by pointer meeting
If the fast pointer meets the slow pointer, a cycle exists in the linked list.Final Answer:
Use two pointers moving at different speeds to detect a cycle -> Option AQuick Check:
Two pointers at different speeds = cycle detection [OK]
- Thinking counting nodes detects cycle
- Assuming reversing list helps detect cycle
- Confusing hash set method with Floyd's algorithm
Solution
Step 1: Understand fast pointer movement
The fast pointer moves two steps at a time to catch up with the slow pointer.Step 2: Identify correct syntax
Moving two nodes ahead is done by fast = fast.next.next.Final Answer:
fast = fast.next.next -> Option BQuick Check:
Fast pointer moves two steps = fast.next.next [OK]
- Moving fast pointer only one step
- Trying to move fast pointer three steps
- Using invalid pointer like prev in singly linked list
class Node:
def __init__(self, val):
self.val = val
self.next = None
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = head.next # cycle here
def has_cycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
print(has_cycle(head))Solution
Step 1: Analyze linked list structure
Nodes 1->2->3 and then 3 points back to 2, creating a cycle.Step 2: Trace Floyd's algorithm
Slow and fast pointers will meet inside the cycle, so function returns True.Final Answer:
True -> Option AQuick Check:
Cycle exists, so output = True [OK]
- Ignoring cycle creation line
- Assuming no cycle returns True
- Confusing None return with False
def detect_cycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next
if slow == fast:
return True
return FalseSolution
Step 1: Check pointer movements
Fast pointer should move two steps (fast = fast.next.next), but here it moves one step.Step 2: Understand impact on cycle detection
Moving one step slows fast pointer, so it may never meet slow pointer correctly.Final Answer:
fast pointer moves only one step instead of two -> Option DQuick Check:
Fast pointer must move two steps [OK]
- Moving fast pointer one step
- Confusing slow pointer movement
- Forgetting to check fast and fast.next
Solution
Step 1: Detect cycle using Floyd's algorithm
Use slow and fast pointers to find meeting point inside cycle.Step 2: Find cycle start node
Reset slow to head, then move slow and fast one step at a time until they meet; meeting point is cycle start.Final Answer:
After detecting cycle, reset slow to head and move both pointers one step until they meet -> Option CQuick Check:
Reset slow and move both pointers one step to find cycle start [OK]
- Trying to count nodes to find cycle start
- Using reversal which doesn't help here
- Confusing hash set method with Floyd's approach
Ready to prove it?
Pass the test and this pattern moves unknown
