How about this solution, which – if I'm not mistaken – should fulfill all requirements:
- create a second array
- run through all elements of the input array
- for each number set the respective key in the second array to true
- run through the second array and return the first key which value comes back as
undefined
- if no match is found, return
1
, so it will work for an empty input array as well
function findNumber(values) {
let result = [];
for (let i = 0; i < values.length; ++i) {
if (0 <= values[i]) {
result[values[i]] = true;
}
}
for (let i = 1; i <= result.length; ++i) {
if (undefined === result[i]) {
return i;
}
}
return 1
}
Patrick and I had a discussion about the real time performance of our solutions (Here's Patrick's elegant solution using Set
). We set up a test, containing around 1000 elements in the input array, including lots of negative values. You can try the test yourself.