Store counts of all elements .
Dictionary < int , int > count = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . ContainsKey ( a [ i ] ) ) { count [ a [ i ] ] = count [ a [ i ] ] + 1 ; } else { count . Add ( a [ i ] , 1 ) ; } } int next_missing = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . ContainsKey ( a [ i ] ) && count [ a [ i ] ] != 1 a [ i ] > n a [ i ] < 1 ) { count [ a [ i ] ] = count [ a [ i ] ] - 1 ;