# Find the Duplicate Number in Python

PythonServer Side ProgrammingProgramming

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 −

• a := nums and b := nums
• while True
• a := nums[nums[a]]
• b := nums[b]
• if a = b, then break
• ptr := nums
• while ptr is not b
• ptr := nums[ptr]
• b := nums[b]
• return ptr

Let us see the following implementation to get better understanding −

## Example

Live Demo

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]))

## Input

[3,1,3,4,2]

## Output

3