w3resource

Python: Find the first duplicate element in a given array of integers


15. Find the First Duplicate Element in an Array

Write a Python program to find the first duplicate element in a given array of integers. Return -1 if there are no such elements.

Sample Solution:

Python Code :

def find_first_duplicate(nums):
    num_set = set()
    no_duplicate = -1

    for i in range(len(nums)):

        if nums[i] in num_set:
            return nums[i]
        else:
            num_set.add(nums[i])

    return no_duplicate

print(find_first_duplicate([1, 2, 3, 4, 4, 5]))
print(find_first_duplicate([1, 2, 3, 4]))
print(find_first_duplicate([1, 1, 2, 3, 3, 2, 2]))

Sample Output:

4
-1
1

For more Practice: Solve these Related Problems:

  • Write a Python program to iterate through an array and return the first element that repeats, or -1 if none exist.
  • Write a Python program to use a set to track seen elements and output the first duplicate encountered.
  • Write a Python program to implement a function that returns both the first duplicate element and its index from an array.
  • Write a Python program to use recursion to identify the first duplicate element in an array.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to find if a given array of integers contains any duplicate element. Return true if any value appears at least twice in the said array and return false if every element is distinct.
Next: Write a Python program to check whether it follows the sequence given in the patterns array.

What is the difficulty level of this exercise?

Based on 68 votes, average difficulty level of this exercise is Hard .

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.