Returns count of words with frequency exactly 2.
static int countWords ( String [ ] str , int n ) { Dictionary < String , int > m = new Dictionary < String , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( str [ i ] ) ) { int get = m [ str [ i ] ] ; m . Remove ( str [ i ] ) ; m . Add ( str [ i ] , get + 1 ) ; } else { m . Add ( str [ i ] , 1 ) ; } } int res = 0 ; foreach ( KeyValuePair < String , int > it in m ) { if ( it . Value == 2 ) res ++ ; } return res ; }