Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 05:01
Show Gist options
  • Save pjcodesjs/db9e85e55fa15a942bc19973a77ecd38 to your computer and use it in GitHub Desktop.
Save pjcodesjs/db9e85e55fa15a942bc19973a77ecd38 to your computer and use it in GitHub Desktop.
function smallestMissingPositiveNumber(arr) {
arr.sort((a, b) => a - b);
let smallestPositive = 1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === smallestPositive) {
smallestPositive++;
} else if (arr[i] > smallestPositive) {
return smallestPositive;
}
}
return arr[arr.length - 1] + 1;
}
// TEST
const arr = [3, 4, -1, 1];
const smallestMissing = smallestMissingPositiveNumber(arr);
console.log(smallestMissing); // output: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment