Created
March 12, 2023 05:01
-
-
Save pjcodesjs/db9e85e55fa15a942bc19973a77ecd38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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