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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

19 lines
Python 3.9+
def 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

stdout
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

  1. Use a set instead of a dictionary when you only need membership, not the first index
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.