The task was to take an array and return the earliest duplicate, and if there are none return -1. I wrote it like this:
function firstDuplicate(a) {
let singles = [];
for (let i = 0; i < a.length; i++) {
if (singles.indexOf(a[i]) == -1) {
singles.push(a[i]);
}
else {
return a[i];
}
}
return -1;
}
It passed all tests except the hidden speed test. Is there another way to write this faster in JS? I saw a Java solution that used sets instead of arrays but I wanted to stick with JS.
array#indexOfworks. It will search from the starting position to the ending position, each time. The search is inO(n)which is pretty slow. There are multiple ways of speeding this up, they all include using a different strategy / data-structure. Better data-structures areHashSet(contains inO(1)),TreeSet(contains inO(log n)). Better strategies when sticking to arrays are search algorithms likeBinarySearchor sorting techniques likeQuickSort. I am sure there are some implementations available in JS already.