Last active
May 15, 2018 00:09
-
-
Save richogreen/6aa93a5b812578a2840a6bf2bda9af94 to your computer and use it in GitHub Desktop.
JavaScript - Find the smallest missing positive integer from an unsorted integer array
This file contains hidden or 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
This problem was asked by Stripe. | |
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. | |
You can modify the input array in-place. | |
Source: Daily Coding Problem (dailycodingproblem.com) |
This file contains hidden or 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 test1 = [1, 2, 0] // Output: 3 | |
const test2 = [3, 4, -1, 1] // Output: 2 | |
const test3 = [7,8,9,11,12] // Output: 1 | |
const firstMissingPositive = (inputArray) => { | |
// Re-order array lowest to highest (mutation OK) | |
inputArray.sort((a, b) => a - b) | |
// Remove negative numbers | |
const cleanArray = inputArray.filter((n) => n > 0) | |
// Check for an index where array[i] != i + 1, if it exists than the answer is i + 1 | |
for (i = 0; i < cleanArray.length; i++) { | |
if (cleanArray[i] != i + 1) { | |
return i + 1 | |
} | |
} | |
// Otherwise answer is array length + 1 | |
return cleanArray.length + 1 | |
} | |
const result = firstMissingPositive(test1) | |
document.write("The lowest possible number is: " + result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment