Store counts of all elements .
unordered_map < int , int > count ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int next_missing = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ a [ i ] ] != 1 a [ i ] > n a [ i ] < 1 ) { count [ a [ i ] ] -- ;