Skip to content

Instantly share code, notes, and snippets.

@debonx
Last active September 30, 2022 09:36
Show Gist options
  • Save debonx/b6982b5c3c2edaf5a3412654ef34e45b to your computer and use it in GitHub Desktop.
Save debonx/b6982b5c3c2edaf5a3412654ef34e45b to your computer and use it in GitHub Desktop.
JavaScript: Simple function to find positive missing integers in Array of numbers.
/* Write a function solution(A); that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000]. */
const A = [-1, -4];
function solution(A) {
let max = A.reduce((acc, val) => acc > val ? acc : val);
let missing = 1;
for (let i = max + 1; i > 0; i--) {
found = A.find(el => el == i);
if(found === undefined) {
missing = i;
}
}
return missing;
}
console.log(solution(A));
@chrisgate
Copy link

below come with 100%:

function solution(A){
let counter = 0;
A.sort(function (a, b) {
return a - b;
});

for (let i = 0; i < A.length; i++) {
const element = A[i];
if (element > 0) {
if (element != counter) {
counter++;
}
if (element == counter) {
continue;
}
return counter;
}
}
counter++;
return counter;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment