Skip to content

Instantly share code, notes, and snippets.

@emrecan-s
Last active February 10, 2020 23:43
Show Gist options
  • Save emrecan-s/90857d91746c8953f883a75e1f2786d4 to your computer and use it in GitHub Desktop.
Save emrecan-s/90857d91746c8953f883a75e1f2786d4 to your computer and use it in GitHub Desktop.
Returns the smallest positive integer (greater than 0) that does not occur in Array.
//Sample Arrays
const A = [1, 3, 6, 4, 1, 2];
const B = [-1 - 10, 0, 2, 3, 5];
const C = [1, 2, 3, 500];
function solution(test) {
//Remove duplicates
let unique = [...new Set(test)];
//Sort from lowest value
let sorted = unique.sort();
//get minimum value
let min = sorted[0];
//Get maximum value
let max = sorted[sorted.length - 1] + 1;
//Array for comparison
let x = [];
//If the minimum value less than 0 returns 1 as a smallest positive integer
if (min < 0) {
return 1;
}
//Creating an array for comparison to find the missing smaller positive integer
for (var i = min; i < max; i++) {
if (i !== 0) {
x.push(i);
}
}
//Both array is the same,returns last element's value+1
if (JSON.stringify(x) == JSON.stringify(sorted)) {
return max;
}
//Finds the smallest missing value
for (var i = min; i < max; i++) {
if (sorted.indexOf(i) === -1 && i !== 0) {
return i;
}
}
}
solution(C);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment