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[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

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def findDuplicate(self, nums):
      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
ob1 = Solution()
print(ob1.findDuplicate([3,1,3,4,2]))

Input

[3,1,3,4,2]

Output

3
raja
Published on 05-Feb-2020 15:02:51
Advertisements