Find the Duplicate Number in Python


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[0] and b := nums[0]

  • while True

    • a := nums[nums[a]]

    • b := nums[b]

    • if a = b, then break

  • ptr := nums[0]

  • while ptr is not b

    • ptr := nums[ptr]

    • b := nums[b]

  • return ptr

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def findDuplicate(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      hare = nums[0]
      tortoise = nums[0]
      while True:
         hare = nums[nums[hare]]
         tortoise = nums[tortoise]
         if hare == tortoise:
            break
      ptr = nums[0]
      while ptr!=tortoise:
         ptr = nums[ptr]
         tortoise = nums[tortoise]
      return ptr

Input

[3,1,3,4,2]

Output

3
raja
Published on 05-Feb-2020 10:32:51
Advertisements