function firstMissingPositive(arr) {
const size = arr.length;
// Step 1: Place each number in its correct position if possible
let i = 0;
while (i < size) {
const correctPos = arr[i] - 1;
if (arr[i] > 0 && arr[i] <= size && arr[i] !== arr[correctPos]) {
// Swap arr[i] with arr[correctPos]
[arr[i], arr[correctPos]] = [arr[correctPos], arr[i]];
} else {
i++;
}
}
// Step 2: Find the first missing positive integer
for (i = 0; i < size; i++) {
if (arr[i] !== i + 1) {
return i + 1;
}
}
// If all numbers are in place, the missing integer is n + 1
return n + 1;
}
const arr = [3, 4, -1, 1];
const missing = firstMissingPositive(arr);
console.log('The first missing smallest positive integer is:', missing);
/*
run:
The first missing smallest positive integer is: 2
*/