I was tasked with writing a function that finds the value of an element that is the first duplicate in an array to be encountered. For the array
[2, 1, 3, 5, 3, 2]
The answer is 3, not 2.
for an array like this:
[5, 3, 8, 2]
(no dups) the answer is -1.
I wrote this function:
def solution(a):
# return if no dups
if len(set(a)) == len(a):
return -1
unique = []
for e in a:
if e in unique:
return e
else:
unique.append(e)
return -1
It does fine with small test inputs but it takes too long on large ones. How can I speed it up?
I tried this same algorithm in Perl on the same data and it processed all the inputs in time.
sub solution {
my ($a) = @_;
my %h;
foreach my $e (@{$a}) {
if (exists($h{$e})) {
return $e;
} else {
$h{$e}++;
}
}
return -1;
}