Problem Description
Determine if a given linked list has a cycle in it. A cycle occurs when a node’s next pointer points to a previous node in the list. Return true if a cycle exists; otherwise, return false.
Key Insights
- Use two pointers (slow and fast) to traverse the list.
- The fast pointer moves two steps at a time and the slow pointer moves one step.
- If the fast pointer ever meets the slow pointer, a cycle exists.
- If the fast pointer reaches the end of the list (null), the list has no cycle.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes in the linked list. Space Complexity: O(1) as only two pointers are used.
Solution
We use the Floyd's Cycle Detection algorithm (Tortoise and Hare approach). Two pointers, slow and fast, are initialized at the head of the list. The slow pointer moves one step at a time while the fast pointer moves two steps. If the linked list has a cycle, the fast pointer will eventually meet the slow pointer. If the fast pointer reaches the end (i.e., a null pointer), the linked list does not have a cycle.