Skip to content

Instantly share code, notes, and snippets.

@surajhell88
Last active May 19, 2018 09:03
Show Gist options
  • Save surajhell88/7fb5be50e3e1e219e03e6991207fb23d to your computer and use it in GitHub Desktop.
Save surajhell88/7fb5be50e3e1e219e03e6991207fb23d to your computer and use it in GitHub Desktop.
Get the first missing positive integer

Search Missing Integer in a given array of Integers

For eg.

  1. searchMissingPositiveInteger([1,4,123]) // should give 2
  2. searchMissingPositiveInteger([-12, -3]) // should give 1
  3. searchMissingPositiveInteger([1, 2, ... , 999]) // should give 1000
function makeHashmap(array) { // create hash map out of array
var hash = {};
array.reduce(function (next, value) {
return hash[value] = value;
}, hash);
return hash;
}
function searchMissingPositiveInteger(arrOfIntegers) {
var sortedArrOfIntergers = arrOfIntegers.sort(function(a, b){return a-b});
var totalLength = sortedArrOfIntergers.length;
var lastInteger = sortedArrOfIntergers[totalLength - 1];
if (lastInteger < 0) return 1; // return 1 if the last integer is negative
var hashOfIt = makeHashmap(sortedArrOfIntergers); // create hash of array for O(N) complexity
for (var i = 1; i <= lastInteger; i++) {
if(!hashOfIt[i]) return i; // search for not existing integer in the hash
}
return lastInteger + 1; // add 1 to last integer if couldn't find the missing positive integer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment