Suppose we have an array nums containing n + 1 integers. The members are in range 1 to n. prove that at least one duplicate number must be there. Assume that there is only one duplicate number, we have to find that duplicate element. So if the array is like [1,3,4,2,2], then the duplicate element will be 2.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def findDuplicate(self, nums): hare = nums tortoise = nums while True: hare = nums[nums[hare]] tortoise = nums[tortoise] if hare == tortoise: break ptr = nums while ptr!=tortoise: ptr = nums[ptr] tortoise = nums[tortoise] return ptr ob1 = Solution() print(ob1.findDuplicate([3,1,3,4,2]))