In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri
JavaScript:
let findFirstMissingNumber = ( arr ) => {
// Sort array and find the index of the lowest positive element.
let sortedArr = arr.sort( (a,b) => a-b );
const lowestPositiveIndex = arr.findIndex( (element) => element > 0 );
// Starting from the lowest positive element
// check upwards if we have the next integer in the array.
let i = lowestPositiveIndex;
while( i < sortedArr.length ) {
if ( sortedArr[ i + 1 ] !== sortedArr[ i ] + 1 ) {
return sortedArr[ i ] + 1
} else {
i += 1;
}
}
}
console.log( findFirstMissingNumber( [3, 4, -1, 1, 1] ) ); // should give 2
console.log( findFirstMissingNumber( [0, 1, 2, 0] ) ); // should give 3