function firstDuplicate(a) {
var numbers = {},
res;
foo:
for (var i = 0; i < a.length; i++) {
for (var j = i + 1; j < a.length; j++) {
if (a[i] === a[j]) {
numbers[a[i]] = j - i;
if (j - i === 1 ) {
break foo;
}
}
}
}
var keys = Object.keys(numbers),
res = keys[0];
keys.forEach(function (v) {
res = numbers[res] > numbers[v] ? v : res;
});
console.log(res);
return res === undefined ? -1 : Number(res);
}
This function returns the first duplicate value in the array of numbers.
I want to decrease its execution time. What changes should I do?
Examples
- For
a = [2, 3, 3, 1, 5, 2], the output should befirstDuplicate(a) = 3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3.
- For
a = [2, 4, 3, 5, 1], the output should befirstDuplicate(a) = -1.
numbers[a[i]]gets overridden so that it only looks at the last pair of duplicates for each value ofa[i]. So ifa = ['a', 'a', 'b', 'a'], then it will find the (1,3) pair instead of the (0,1) pair. But yes, this definitely needs more clarity.a = [4, 4, 9, 9]you want to return4. What ifa = [4, 9, 9, 4]?