- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find duplicate item from a list of elements in Python
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
Example
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] print(solve(nums))
Input
[2,1,4,3,5,4]
Output
4
Advertisements