Code#1 which uses a while True loop to check the intersection of elements/nodes. Output is 2, which is correct since it is the only duplicate:
nums=[1,3,4,2,2]
slow = nums[0]
fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# Phase 2: Find the entrance to the cycle
ptr1 = nums[0]
ptr2 = slow
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
print(ptr1)
Code#2 which uses while slow!=fast-break to achieve the same, but the output is 1:
nums=[1,3,4,2,2]
slow = nums[0]
fast = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
# Phase 2: Find the entrance to the cycle
ptr1 = nums[0]
ptr2 = slow
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
print(ptr1)
I believe both the while loops are essentially the same. Please help.
Not sure why both the while loops are behaving differently. Or maybe I am missing something very basic.