Store counts of all elements .
var count = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( count . has ( a [ i ] ) ) count . set ( a [ i ] , count . get ( a [ i ] ) + 1 ) else count . set ( a [ i ] , 1 ) } var next_missing = 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( count . get ( a [ i ] ) != 1 a [ i ] > n a [ i ] < 1 ) { count . set ( a [ i ] , count . get ( a [ i ] ) - 1 ) ;