text: Check if a String contains any index with more than K active characters | C # program to implement the above approach ; Function to check if any index contains more than K active characters ; Store the last occurrence of each character in the map . ; Stores the active characters ; Insert the character ; If the size of set exceeds K ; Remove the character from set if i is the last index of the current character ; Driver code
code: using System ; using System . Collections . Generic ; class GFG { static String checkString ( String s , int K ) { int n = s . Length ; Dictionary < char , int > mp = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( s [ i ] ) ) mp [ s [ i ] ] = i ; else mp . Add ( s [ i ] , i ) ; } int f = 0 ; HashSet < char > st = new HashSet < char > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { st . Add ( s [ i ] ) ; if ( st . Count > K ) { f = 1 ; break ; } if ( mp [ s [ i ] ] == i ) st . Remove ( s [ i ] ) ; } return ( f == 1 ? " Yes " : " No " ) ; } public static void Main ( String [ ] args ) { String s = " aabbcdca " ; int k = 2 ; Console . WriteLine ( checkString ( s , k ) ) ; } }