Code Explanation:
Function Purpose
def has_cycle(nums):
This function checks whether there is a cycle in a list of numbers.
It uses the Floyd’s Cycle Detection Algorithm (also known as Tortoise and Hare) to detect cycles without extra space.
Initialize Pointers
slow = fast = 0
Two pointers, slow and fast, are both initialized at index 0.
slow will move one step at a time, while fast moves two steps.
The idea is: if there is a cycle, slow and fast will eventually meet inside the cycle.
Loop to Traverse the List
while fast < len(nums) and nums[fast] < len(nums):
The loop continues as long as:
fast is a valid index (< len(nums))
nums[fast] is also a valid index (we’re using it as a pointer too)
This prevents index out of range errors when accessing nums[nums[fast]].
Move Pointers
slow = nums[slow]
fast = nums[nums[fast]]
slow = nums[slow] → move slow pointer one step forward.
fast = nums[nums[fast]] → move fast pointer two steps forward.
This simulates two pointers moving at different speeds through the list.
Cycle Detection Condition
if slow == fast:
return True
If at any point slow and fast pointers meet, a cycle is detected.
In a cycle, fast-moving and slow-moving pointers will eventually catch up.
No Cycle Case
return False
If the loop exits without the pointers meeting, there’s no cycle in the list.
Function Call and Output
print(has_cycle([1, 2, 3, 4, 2]))
The list is:
Index → Value
0 → 1, 1 → 2, 2 → 3, 3 → 4, 4 → 2
This forms a cycle: 2 → 3 → 4 → 2...
Pointers will move like this:
slow = 0 → 1 → 2 → 3
fast = 0 → 2 → 4 → 3 → 2
At some point, slow == fast == 2, so:
Output:
True
.png)

0 Comments:
Post a Comment