For eg.
searchMissingPositiveInteger([1,4,123]) // should give 2searchMissingPositiveInteger([-12, -3]) // should give 1searchMissingPositiveInteger([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 | |
| } |