Back
Problem SolvingEasyNew
How would you check if a linked list has a cycle?
Two pointers moving at different speeds.
Ideal Answer
Use Floyd's cycle detection (tortoise and hare):
- Start slow and fast pointers at the head.
- Move slow one step and fast two steps each iteration.
- If they meet, a cycle exists.
- If fast reaches null, no cycle.
Time O(n), space O(1).
Alternative: store visited nodes in a Set — simpler but O(n) space.