Missing integer in JS

Michael Horowitz
1 min readFeb 8, 2021

--

The missing integer problem asks for the return of the smallest positive integer (greater than 0) that does not occur in the given array. 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.

To start we set a variable for our smallest number.

let min = 1

We set the minimum to 1 because the problem stats greater than 0. Next, we can sort our array from lowest to highest.

A.sort(function(a,b){a - b});

Once we have a sorted array we loop through the array and check each number if they are positive and are equal to our current minimum number.

for (let i in A) {             
if (A[i] > -1 && A[i] == min) {
min++;
}
}

After we finish looping through we return our min.

return min;

--

--

No responses yet