text: Check if a string can be split into two strings with same number of K | C ++ implementation of the above approach ; Function to print the arrangement of characters ; Stores frequency of characters ; Count the character having frequency K ; Count the character having frequency greater than K and not equal to 2 K ; Case 1 ; Case 2 ; Case 3 ; If all cases fail ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void DivideString ( string s , int n , int k ) { int i , c = 0 , no = 1 ; int c1 = 0 , c2 = 0 ; int fr [ 26 ] = { 0 } ; string ans = " " ; for ( i = 0 ; i < n ; i ++ ) { fr [ s [ i ] - ' a ' ] ++ ; } char ch , ch1 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( fr [ i ] == k ) { c ++ ; } if ( fr [ i ] > k && fr [ i ] != 2 * k ) { c1 ++ ; ch = i + ' a ' ; } if ( fr [ i ] == 2 * k ) { c2 ++ ; ch1 = i + ' a ' ; } } for ( i = 0 ; i < n ; i ++ ) ans = ans + "1" ; map < char , int > mp ; if ( c % 2 == 0 c1 > 0 c2 > 0 ) { for ( i = 0 ; i < n ; i ++ ) { if ( fr [ s [ i ] - ' a ' ] == k ) { if ( mp . find ( s [ i ] ) != mp . end ( ) ) { ans [ i ] = '2' ; } else { if ( no <= ( c / 2 ) ) { ans [ i ] = '2' ; no ++ ; mp [ s [ i ] ] = 1 ; } } } } if ( c % 2 == 1 && c1 > 0 ) { no = 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ch && no <= k ) { ans [ i ] = '2' ; no ++ ; } } } if ( c % 2 == 1 && c1 == 0 ) { no = 1 ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ch1 && no <= k ) { ans [ i ] = '2' ; no ++ ; } if ( fr [ s [ i ] - ' a ' ] == k && flag == 0 && ans [ i ] == '1' ) { ans [ i ] = '2' ; flag = 1 ; } } } cout << ans << endl ; } else { cout << " NO " << endl ; } } int main ( ) { string S = " abbbccc " ; int N = S . size ( ) ; int K = 1 ; DivideString ( S , N , K ) ; return 0 ; }