DEV Community

Cover image for Smallest positive missing number

Smallest positive missing number

Tisha Agarwal on January 30, 2022

Find the smallest positive missing number in the given array. Example: [0, -10, 1, 3, -20], Ans = 2 Constrains: 1<=N<=10^6 -10^6<=Ai<=1...
Collapse
 
lexlohr profile image
Alex Lohr • Edited

In JS, the solution would be filtering negative numbers and comparing to the index:

const smallestMissingPositiveNumber =
  (array) => array
    .filter(num => num >= 0)
    .find((num, idx) => num !== idx) - 1
Enter fullscreen mode Exit fullscreen mode

Obviously, if the positive numbers don't start at zero, we need to find out the starting number and add that as difference.

Collapse
 
lexlohr profile image
Alex Lohr

Since filter already creates a new array, there's no need to destructure it.

The only "real world application" I can think of is usually job interviews.