I had a job interview in which I had a couple code exercises. One of which was write a function that can take a numerical array and return either the first duplicated number or -1 in the case of no duplication. I wrote the following function that answers the exercise but failed on efficiency. The problem was, I was not given a sufficient answer, so for a learning point, can someone help me write this function more efficient.
function myFunc(arr) {
for (var i = 0; i < arr.length; i++) {
for (var x = 0; x < arr.length; x++) {
if ((arr[i]==arr[x]) && ( i > x)) {
return arr[i];
}
}
}
return -1;
}
examples of returns:
arr = {8, 4, 6, 2, 6, 4, 7, 9, 5, 8} returns 6
arr = {2, 3, 3, 1, 5, 2} returns 3