'''
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. 
In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. 
If there are no such elements, return -1.

Examples:
For a = [2, 2] output = 2
For a = [2, 1, 3, 5, 3, 2] output = 3
For a = [2, 4, 3, 5, 1] output = -1

'''

def solution(a):
    mySet=set()
    for el in a:
        if el in mySet:
            return el
        mySet.add(el)
    return -1

print(
    solution([2, 1, 3, 5, 3, 2])
     ) #Output 3
print(
    solution([2, 4, 3, 5, 1])
    ) #Output -1
print(
    solution([1, 1, 2, 2, 1])
    ) #Output 1
print(
    solution([9])
    ) #Output -1

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: