Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | Python3 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
from collections import defaultdict NEW_LINE import math NEW_LINE def isPowerOfTwo ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( math . ceil ( math . log2 ( n ) ) == math . floor ( math . log2 ( n ) ) ) NEW_LINE DEDENT def printArray ( res ) : NEW_LINE INDENT res . sort ( ) NEW_LINE for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def sortedStrings ( S , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE res = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT st = " " NEW_LINE for j in range ( len ( S [ i ] ) ) : NEW_LINE INDENT freq [ S [ i ] [ j ] ] += 1 NEW_LINE DEDENT for i in freq : NEW_LINE INDENT if ( isPowerOfTwo ( freq [ i ] ) ) : NEW_LINE INDENT for j in range ( freq [ i ] ) : NEW_LINE INDENT st += i NEW_LINE DEDENT DEDENT DEDENT freq . clear ( ) NEW_LINE if ( len ( st ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT st = list ( st ) NEW_LINE st . sort ( reverse = True ) NEW_LINE st = ' ' . join ( st ) NEW_LINE res . append ( st ) NEW_LINE DEDENT printArray ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " aaacbb " , " geeks " , " aaa " ] NEW_LINE N = len ( arr ) NEW_LINE sortedStrings ( arr , N ) NEW_LINE DEDENT