Return first duplicate This is a problem from Codesignal.
The guaranteed constraints are 1 &lt;= a.length &lt;= 10^5, and 1 &lt;= a[i] &lt;= a.length.
You have to return the first duplicate encoutered in a, or -1 if no duplicate is found.
def firstDuplicate(a):

    b = [0] * 100001
    for num in a:
        if b[num] == 1:
            return num
        else:
            b[num] = 1
    return -1

Is there a better way to do this? Perhaps faster or using less memory? The unused 0 index in the b array also doesn't feel very clean.
I'll propose an alternate implementation, because dictionaries are good at storing key-value pairs and you don't care about the value:
def first_duplicate(given_list):
    seen = set()
    for value in given_list:
        if value in seen:
            return value
        seen.add(value)
    return -1

A set will buy you basically the same behaviour as the &quot;keys of a dictionary&quot; for these purposes.