0

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.

1 Answers1

0

I believe this can help you figure it out

# code 1
nums=[1,3,4,2,2]

slow = nums[0]
fast = nums[0]

while True:
    slow = nums[slow]
    print("in while - slow", slow)
    fast = nums[nums[fast]]
    print("in while - fast", fast)
    if slow == fast:
        break

# Phase 2: Find the entrance to the cycle
ptr1 = nums[0]
ptr2 = slow

while ptr1 != ptr2:
    ptr1 = nums[ptr1]
    print("in while 2 - ptr1", ptr1)
    ptr2 = nums[ptr2]
    print("in while 2 - ptr2", ptr2)

print(ptr1)

And this output is

in while - slow 3
in while - fast 2
in while - slow 2
in while - fast 2
in while 2 - ptr1 3
in while 2 - ptr2 4
in while 2 - ptr1 2
in while 2 - ptr2 2
2

And this is code 2, the output is 1 as you expected.
Never enter to the both While loop.

#code 2
nums=[1,3,4,2,2]

slow = nums[0]
fast = nums[0]

while slow != fast:
    slow = nums[slow]
    print("in while - slow", slow)
    fast = nums[nums[fast]]
    print("in while - fast", 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)

The output is

1
8823
  • 66
  • 6