Find First Duplicate Index in Python
Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.
Python code
19 linesdef find_first_duplicate(arr):
seen = {}
for index, value in enumerate(arr):
if value in seen:
return index
seen[value] = index
return -1
if __name__ == "__main__":
test_array = [3, 5, 2, 8, 5, 1, 2]
result = find_first_duplicate(test_array)
print(f"Array: {test_array}")
print(f"First duplicate index: {result}")
print(f"First duplicate value: {test_array[result] if result != -1 else 'None'}")
no_dup = [1, 2, 3, 4, 5]
result2 = find_first_duplicate(no_dup)
print(f"\nArray: {no_dup}")
print(f"First duplicate index: {result2}")
Output
Array: [3, 5, 2, 8, 5, 1, 2]
First duplicate index: 4
First duplicate value: 5
Array: [1, 2, 3, 4, 5]
First duplicate index: -1
How it works
The function uses a dictionary seen to store each element's first index as it iterates through the array with enumerate. When an element is already in seen, it means a duplicate occurred, and the current index is the position of that duplicate. Since the loop processes from left to right, the first duplicate found is the earliest one. If no duplicates exist, the function returns -1 as a sentinel. This approach achieves O(n) time and O(n) space.
Common mistakes
- Returning the index of the first occurrence instead of the duplicate's index
- Forgetting to handle the no-duplicate case and accessing an invalid index
- Using a list instead of a set/dict, which makes lookup O(n) and the whole function O(n^2)
Variations
- Use a set instead of a dictionary when you only need membership, not the first index
- Collect all duplicates with a dict and find the minimum index via min()
Real-world use cases
- Detecting duplicate user IDs in a transaction batch to flag potential data errors.
- Checking for repeated configuration keys in an ordered list to warn about overrides.
- Identifying the first repeated item in a log sequence for anomaly detection.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.