How To Find The First Duplicate Element In A Given Array Of Integers In Python
Chapter:
Python
Last Updated:
27-05-2023 12:41:05 UTC
Program:
/* ............... START ............... */
def find_first_duplicate(arr):
num_set = set()
for num in arr:
if num in num_set:
return num
num_set.add(num)
# If no duplicates found
return None
array = [2, 5, 6, 3, 2, 7, 8, 5]
result = find_first_duplicate(array)
if result:
print("First duplicate element:", result)
else:
print("No duplicate element found.")
/* ............... END ............... */
Output
First duplicate element: 2
Notes:
-
In this example, the find_first_duplicate function uses a set (num_set) to keep track of the numbers seen so far. It iterates over the array and checks if each number is already present in the set. If it is, it means the number is a duplicate, and the function returns that number as the first duplicate element. If no duplicates are found, it returns None.
- In the provided array [2, 5, 6, 3, 2, 7, 8, 5], the first duplicate element is 2.