Data Structures · Visualization
Linked List: Detect Cycle
Linked List
A cycle happens when some node's 'next' pointer loops back to an earlier node instead of eventually reaching null, so traversal never ends. Time: O(n). Space: O(1).
Big-O: Lookup O(n); insert/delete at head O(1).
Linked List: Detect Cycle
Linked ListA cycle happens when some node's 'next' pointer loops back to an earlier node instead of eventually reaching null, so traversal never ends. This is detected using Floyd's 'tortoise and hare' technique: a slow pointer and a fast pointer move through the list, and if there is a cycle, the fast pointer will eventually lap the slow pointer and they will meet.
How Detect Cycle Works
- Set slow and fast pointers to the head.
- Move slow one step and fast two steps at a time.
- If fast reaches null (or fast.next is null), there is no cycle.
- If slow and fast ever point to the same node, a cycle exists.
Detect Cycle Worked Example
Input: A list where node 5's next incorrectly points back to node 2
- slow and fast both start at node 1
- Repeat the 1-step / 2-step movement
- Because of the loop, fast eventually 'wraps around' and catches up to slow
- slow === fast → cycle detected
Output: true (cycle found)
Press ▶ Run to watch it step by step.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next # 1 step
fast = fast.next.next # 2 steps
if slow is fast:
return True # they met -> cycle
return False
# Floyd's tortoise and hare
# example: detect cycle on [10, 20, 30]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Detect Cycle Time & Space Complexity
When to Use Detect Cycle
- Detecting corrupted or accidentally circular data structures
- Validating linked list integrity before processing it
- A classic interview question demonstrating the two-pointer technique
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.