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: #include <bits/stdc++.h> NEW_LINE using namespace std ; string checkString ( string s , int K ) { int n = s . length ( ) ; unordered_map < char , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ s [ i ] ] = i ; } int cnt = 0 , f = 0 ; unordered_set < int > st ; for ( int i = 0 ; i < n ; i ++ ) { st . insert ( s [ i ] ) ; if ( st . size ( ) > K ) { f = 1 ; break ; } if ( mp [ s [ i ] ] == i ) st . erase ( s [ i ] ) ; } return ( f == 1 ? " Yes " : " No " ) ; } int main ( ) { string s = " aabbcdca " ; int k = 2 ; cout << checkString ( s , k ) ; return 0 ; }