To keep track of end index of resultant string
int endIndex = 0 ; for ( int i = 0 ; i < chars . size ( ) ; i ++ ) { if ( table [ chars [ i ] ] == 0 ) { table [ chars [ i ] ] = -1 ; chars [ endIndex ++ ] = chars [ i ] ; } } string ans = " " ; for ( int i = 0 ; i < endIndex ; i ++ ) ans += chars [ i ] ; return ans ; }