Linked List Cycle
EasyGiven the head of a linked list, write a function hasCycle to determine if the linked list has a cycle in it. A linked list is said to have a cycle if a node's next pointer points to a previous node in the list, forming a loop. Return true if there is a cycle, otherwise return false.
Example

Our solution detects whether a linked list contains a cycle by employing the Floyd's Tortoise and Hare algorithm. This algorithm uses two pointers, slow and fast, which traverse the linked list at different speeds.
- Initialization: Both
slowandfastpointers start at the head of the linked list. - Traversal:
- Slow Pointer: Moves one step at a time (
slow = slow->next). - Fast Pointer: Moves two steps at a time (
fast = fast->next->next).
- Slow Pointer: Moves one step at a time (
- Detection:
- If at any point the
slowpointer andfastpointer meet, it indicates the presence of a cycle in the linked list. This is because thefastpointer will loop around and eventually catch up with theslowpointer if a cycle exists. - If the
fastpointer reaches the end of the list (fast == nullptrorfast->next == nullptr), then there is no cycle in the list.
- If at any point the
The algorithm is efficient as it only requires a single pass through the list with constant space complexity. It is straightforward and avoids the need for extra data structures.
Time Complexity: The solution has a time complexity of O(n), where n is the number of nodes in the linked list. This is because the slow and fast pointers will traverse the list at most once each, making the traversal efficient.
Space Complexity: The solution has a space complexity of O(1) since it uses only two pointers and does not require additional space proportional to the input size. This makes the algorithm both space and time efficient.
Related courses






