Program to find duplicate item from a list of elements in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of elements called nums of size n + 1, they are selected from range 1, 2, ..., n. As we know, by pigeonhole principle, there must be a duplicate. We have to find the duplicate. Here our target is to find the task in O(n) time and constant space.

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

To solve this, we will follow these steps −

  • q := sum of all elements present in nums

  • n := size of nums

  • v := floor of ((n - 1)*(n)/2)

  • return q - v


Let us see the following implementation to get better understanding

def solve(nums):
   q = sum(nums)
   n = len(nums)
   v = (n - 1) * (n) // 2
   return q - v

nums = [2,1,4,3,5,4]




Updated on 11-Oct-2021 07:00:09