Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | C ++ program for the above approach ; Function to check if N is power of 2 or not ; Base Case ; Return true if N is power of 2 ; Function to print array of strings in ascending order ; Sort strings in ascending order ; Print the array ; Function to sort the strings after modifying each string according to the given conditions ; Store the frequency of each characters of the string ; Stores the required array of strings ; Traverse the array of strings ; Temporary string ; Stores frequency of each alphabet of the string ; Update frequency of S [ i ] [ j ] ; Traverse the map freq ; Check if the frequency of i . first is a power of 2 ; Update string st ; Clear the map ; Null string ; Sort the string in descending order ; Update res ; Print the array of strings ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } void printArray ( vector < string > res ) { sort ( res . begin ( ) , res . end ( ) ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " ▁ " ; } } void sortedStrings ( string S [ ] , int N ) { unordered_map < char , int > freq ; vector < string > res ; for ( int i = 0 ; i < N ; i ++ ) { string st = " " ; for ( int j = 0 ; j < S [ i ] . size ( ) ; j ++ ) { freq [ S [ i ] [ j ] ] ++ ; } for ( auto i : freq ) { if ( isPowerOfTwo ( i . second ) ) { for ( int j = 0 ; j < i . second ; j ++ ) { st += i . first ; } } } freq . clear ( ) ; if ( st . size ( ) == 0 ) continue ; sort ( st . begin ( ) , st . end ( ) , greater < char > ( ) ) ; res . push_back ( st ) ; } printArray ( res ) ; } int main ( ) { string arr [ ] = { " aaacbb " , " geeks " , " aaa " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortedStrings ( arr , N ) ; return 0 ; }