Program to find duplicate element from n+1 numbers ranging from 1 to n in Python


Suppose we have a list of numbers called nums of length n + 1. These numbers are picked from range 1, 2, ..., n. As we know, using the pigeonhole principle, there must be a duplicate. We have to find that and return it.

So, if the input is like [2, 1, 4, 3, 3], then the output will be 3

To solve this, we will follow these steps −

  • l := size of nums
  • temp := l*(l-1) /2
  • temp_sum := sum of all elements in nums
  • return (temp_sum - temp)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      l = len(nums)
      temp = l*(l-1)/2
      temp_sum = sum(nums)
      return temp_sum-temp
ob = Solution()
print(ob.solve([2, 1, 4, 3, 3]))

Input

[2, 1, 4, 3, 3]

Output

3

Updated on: 06-Oct-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements