Last active
May 1, 2020 20:30
-
-
Save Gosilama/6206e7f24d180d03c1816c6ea1d1d06c to your computer and use it in GitHub Desktop.
Given an array of integers, find the first missing positive integer in linear time and constant space. 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. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
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
const findFirstMissingPositiveInteger = input => { | |
const sortedInput = input.sort((a, b) => { | |
if (a < b) return -1; | |
if (a > b) return 1; | |
return 0; | |
}); | |
const nthInput = input.length - 1; | |
if (sortedInput[nthInput] <= 0) return 1; | |
for (let i = 0; i < nthInput; i++) { | |
if (sortedInput[i] > 0) { | |
const diff = sortedInput[i + 1] - sortedInput[i]; | |
if (diff > 1) return sortedInput[i] + 1; | |
} | |
} | |
return sortedInput[nthInput] + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment