Solution: Linked List Cycle IV
Let’s solve the Linked List Cycle IV problem using the Fast and Slow Pointers pattern.
We'll cover the following
Statement
Given the head of a singly linked list, implement a function to detect and remove any cycle present in the list. A cycle occurs when a node's next
pointer links back to a previous node, forming a loop within the list.
The function must modify the linked list in place, ensuring it remains acyclic while preserving the original node order. If no cycle is found, return the linked list as is.
Constraints:
The number of nodes in the list is in the range
. Node.value
Solution
The Floyd’s Cycle Detection method is used to identify and eliminate cycles efficiently. It begins by initializing two pointers at the head of the linked list. The slow pointer moves one step, and the fast moves two steps to traverse the list. If the two pointers meet, a cycle is detected; otherwise, if fast reaches NULL, the list is cycle-free. To determine the cycle’s starting node, slow is reset to the head, and both pointers move one step at a time until they meet again. Once the cycle’s entry point is found, the algorithm traverses the loop to identify the last node in the cycle, which is the node whose next pointer refers back to the cycle start. Finally, the cycle is removed by setting this last node next to NULL, restoring the linked list to a proper linear structure.
The steps of the algorithm are as follows:
Initialize two pointers,
slow
andfast
, to thehead
node.Traverse the linked list using
slow
andfast
pointers to detect a cycle:Move
slow
, one step forward.Move
fast
, two steps forward.If
slow == fast
, a cycle is detected, and we break out of the loop.
If
fast
reaches NULL, the list is cycle-free and returnhead
.Once a cycle is detected, we need to determine where it begins:
Reset
slow
tohead
.Move both
slow
andfast
, one step at a time, until they meet again. The meeting point is the starting node of the cycle.
To break the cycle, we must locate the last node in the loop:
Start from
fast
, which is now at the cycle’s starting node.Move forward through the cycle until
fast.next == slow
(this identifies the last node in the cycle).
Set
fast.next = NULL
to break the cycle and restore the linked list to a linear structure.Return the
head
of the modified linked list.
Let’s look at the illustration below to better understand the solution.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.