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 implementation of PMCarpan's algorithm
function getMissingInt(array) {
const segArray = array.filter((a) => a > 0);
for (let i = 0; i < segArray.length; i++) {
const value = Math.abs(segArray[i]);
if (value <= segArray.length && segArray[value - 1] > 0) {
segArray[value - 1] *= -1;
}
}
for (let i = 0; i < segArray.length; i++) {
if (segArray[i] > 0) {
return i + 1;
}
}
return segArray.length + 1;
}
console.log(getMissingInt([1, -1, -5, -3, 3, 4, 2, 8]));
console.log(getMissingInt([3, 4, -1, 1]));
console.log(getMissingInt([1, 2, 0]));