Find the smallest positive number missing from an unsorted array | Set 1 | Utility function that puts all non - positive ( 0 and negative ) numbers on left side of arr [ ] and return count of such numbers ; increment count of non - positive integers ; Find the smallest positive missing number in an array that contains all positive integers ; Mark arr [ i ] as visited by making arr [ arr [ i ] - 1 ] negative . Note that 1 is subtracted because index start from 0 and positive numbers start from 1 ; Return the first index value at which is positive ; 1 is added becuase indexes ; Find the smallest positive missing number in an array that contains both positive and negative integers ; First separate positive and negative numbers ; Shift the array and call findMissingPositive for positive part ; Driver code
function segregate ( arr , size ) { let j = 0 , i ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] <= 0 ) { let temp ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; j ++ ; } } return j ; } function findMissingPositive ( arr , size ) { let i ; for ( i = 0 ; i < size ; i ++ ) { let x = Math . abs ( arr [ i ] ) ; if ( x - 1 < size && arr [ x - 1 ] > 0 ) arr [ x - 1 ] = - arr [ x - 1 ] ; } for ( i = 0 ; i < size ; i ++ ) if ( arr [ i ] > 0 ) return i + 1 ; return size + 1 ; } function findMissing ( arr , size ) { let shift = segregate ( arr , size ) ; let arr2 = new Array ( size - shift ) ; let j = 0 ; for ( let i = shift ; i < size ; i ++ ) { arr2 [ j ] = arr [ i ] ; j ++ ; } return findMissingPositive ( arr2 , j ) ; } let arr = [ 0 , 10 , 2 , - 10 , - 20 ] ; let arr_size = arr . length ; let missing = findMissing ( arr , arr_size ) ; document . write ( " " + missing ) ;