GeeksforGeeks App
Open App
Browser
Continue

# Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2

Given an array arr[] consisting of N strings, the task is to sort the array in ascending order after modifying each string by removing all characters that are not perfect power of 2 and then sort the modified string in decreasing order.

Examples:

Input: arr[] = {“aaacbb”, “geeks”, “aaa”}
Output: cbb skgee
Explanation:
Following are the modified strings in the array arr[]:

1. For the string “aaacbb”: The frequency of a is not the power of 2. Therefore, removing ‘a’ modifies the string to “cbb”. Now, sorting the string “cbb” in increasing order of frequency modifies the string to “cbb”.
2. For the string “geeks”: The frequency of every character is a power of 2. Now, sorting the string “geeks” in increasing order of frequency modifies the string to “skgee”.
3. For the string “aaa”: The frequency of a is not the power of 2. Therefore, removing ‘a’ modifies the string to “”.

Therefore, sorting the above strings in increasing order gives {“cbb”, “skgee”}.

Input: S[] = {“c”, “a”, “b”}
Output: a b c

Approach: The given problem can be solved by using the Hashing to store the frequencies of all the characters for each string and then perform the given operations. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## C++

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

## Java

 `// Java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `class` `GFG{` `// Function to check if N is power of``// 2 or not``static` `boolean` `isPowerOfTwo(``int` `n)``{``    ` `    ``// Base Case``    ``if` `(n == ``0``)``        ``return` `false``;` `    ``// Return true if N is power of 2``    ``return` `(Math.ceil(Math.log(n) / Math.log(``2``)) ==``           ``Math.floor(Math.log(n) / Math.log(``2``)));``}` `// Function to print array of strings``// in ascending order``static` `void` `printArray(ArrayList res)``{``    ` `    ``// Sort strings in ascending order``    ``Collections.sort(res);` `    ``// Print the array``    ``for``(``int` `i = ``0``; i < res.size(); i++)``    ``{``        ``System.out.print(res.get(i) + ``" "``);``    ``}``}` `// Function to sort the strings after``// modifying each string according to``// the given conditions``static` `void` `sortedStrings(String S[], ``int` `N)``{``    ` `    ``// Store the frequency of each``    ``// characters of the string``    ``HashMap freq = ``new` `HashMap<>();` `    ``// Stores the required``    ``// array of strings``    ``ArrayList res = ``new` `ArrayList<>();` `    ``// Traverse the array of strings``    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ` `        ``// Temporary string``        ``String st = ``""``;` `        ``// Stores frequency of each``        ``// alphabet of the string``        ``for``(``int` `j = ``0``; j < S[i].length(); j++)``        ``{``            ` `            ``// Update frequency of S[i][j]``            ``freq.put(S[i].charAt(j),``                ``freq.getOrDefault(S[i].charAt(j), ``0``) + ``1``);``        ``}` `        ``// Traverse the map freq``        ``for``(``char` `ch : freq.keySet())``        ``{``            ` `            ``// Check if the frequency``            ``// of i.first is a power of 2``            ``if` `(isPowerOfTwo(freq.get(ch)))``            ``{` `                ``// Update string st``                ``for``(``int` `j = ``0``; j < freq.get(ch); j++)``                ``{``                    ``st += ch;``                ``}``            ``}``        ``}` `        ``// Clear the map``        ``freq.clear();` `        ``// Null string``        ``if` `(st.length() == ``0``)``            ``continue``;` `        ``// Sort the string in``        ``// descending order``        ``char` `myCharArr[] = st.toCharArray();``        ``Arrays.sort(myCharArr);``        ``String ns = ``""``;``        ` `        ``for``(``int` `j = myCharArr.length - ``1``; j >= ``0``; --j)``            ``ns += myCharArr[j];` `        ``// Update res``        ``res.add(ns);``    ``}``    ` `    ``// Print the array of strings``    ``printArray(res);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``String arr[] = { ``"aaacbb"``, ``"geeks"``, ``"aaa"` `};``    ``int` `N = arr.length;``    ` `    ``sortedStrings(arr, N);``}``}` `// This code is contributed by Kingash`

## Python3

 `# Python3 program for the above approach``from` `collections ``import` `defaultdict``import` `math` `# Function to check if N is power of``# 2 or not``def` `isPowerOfTwo(n):` `    ``# Base Case``    ``if` `(n ``=``=` `0``):``        ``return` `False` `    ``# Return true if N is power of 2``    ``return` `(math.ceil(math.log2(n)) ``=``=``            ``math.floor(math.log2(n)))` `# Function to print array of strings``# in ascending order``def` `printArray(res):` `    ``# Sort strings in ascending order``    ``res.sort()` `    ``# Print the array``    ``for` `i ``in` `range``(``len``(res)):``        ``print``(res[i], end ``=` `" "``)` `# Function to sort the strings after``# modifying each string according to``# the given conditions``def` `sortedStrings(S, N):` `    ``# Store the frequency of each``    ``# characters of the string``    ``freq ``=` `defaultdict(``int``)` `    ``# Stores the required``    ``# array of strings``    ``res ``=` `[]` `    ``# Traverse the array of strings``    ``for` `i ``in` `range``(N):` `        ``# Temporary string``        ``st ``=` `""` `        ``# Stores frequency of each``        ``# alphabet of the string``        ``for` `j ``in` `range``(``len``(S[i])):` `            ``# Update frequency of S[i][j]``            ``freq[S[i][j]] ``+``=` `1` `        ``# Traverse the map freq``        ``for` `i ``in` `freq:` `            ``# Check if the frequency``            ``# of i.first is a power of 2``            ``if` `(isPowerOfTwo(freq[i])):` `                ``# Update string st``                ``for` `j ``in` `range``(freq[i]):``                    ``st ``+``=` `i` `        ``# Clear the map``        ``freq.clear()` `        ``# Null string``        ``if` `(``len``(st) ``=``=` `0``):``            ``continue` `        ``# Sort the string in``        ``# descending order``        ``st ``=` `list``(st)``        ``st.sort(reverse``=``True``)``        ``st ``=` `''.join(st)` `        ``# Update res``        ``res.append(st)` `    ``# Print the array of strings``    ``printArray(res)` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[ ``"aaacbb"``, ``"geeks"``, ``"aaa"` `]``    ``N ``=` `len``(arr)``    ` `    ``sortedStrings(arr, N)` `# This code is contributed by ukasp`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `public` `class` `GFG``{` `  ``// Function to check if N is power of``  ``// 2 or not``  ``static` `bool` `isPowerOfTwo(``int` `n)``  ``{` `    ``// Base Case``    ``if` `(n == 0)``      ``return` `false``;` `    ``// Return true if N is power of 2``    ``return` `(Math.Ceiling(Math.Log(n) / Math.Log(2)) ==``            ``Math.Floor(Math.Log(n) / Math.Log(2)));``  ``}` `  ``// Function to print array of strings``  ``// in ascending order``  ``static` `void` `printArray(List<``string``> res)``  ``{` `    ``// Sort strings in ascending order``    ``(res).Sort();` `    ``// Print the array``    ``for``(``int` `i = 0; i < res.Count; i++)``    ``{``      ``Console.Write(res[i] + ``" "``);``    ``}``  ``}` `  ``// Function to sort the strings after``  ``// modifying each string according to``  ``// the given conditions``  ``static` `void` `sortedStrings(``string``[] S, ``int` `N)``  ``{` `    ``// Store the frequency of each``    ``// characters of the string``    ``Dictionary<``char``,``int``> freq = ``new` `Dictionary<``char``,``int``>();` `    ``// Stores the required``    ``// array of strings``    ``List<``string``> res = ``new` `List<``string``>();` `    ``// Traverse the array of strings``    ``for``(``int` `i = 0; i < N; i++)``    ``{` `      ``// Temporary string``      ``string` `st = ``""``;` `      ``// Stores frequency of each``      ``// alphabet of the string``      ``for``(``int` `j = 0; j < S[i].Length; j++)``      ``{` `        ``// Update frequency of S[i][j]``        ``if``(!freq.ContainsKey(S[i][j]))``          ``freq.Add(S[i][j],0);``        ``freq[S[i][j]]++;``      ``}` `      ``// Traverse the map freq``      ``foreach``(KeyValuePair<``char``, ``int``> ch ``in` `freq)``      ``{` `        ``// Check if the frequency``        ``// of i.first is a power of 2``        ``if` `(isPowerOfTwo(freq[ch.Key]))``        ``{` `          ``// Update string st``          ``for``(``int` `j = 0; j < freq[ch.Key]; j++)``          ``{``            ``st += ch.Key;``          ``}``        ``}``      ``}` `      ``// Clear the map``      ``freq.Clear();` `      ``// Null string``      ``if` `(st.Length == 0)``        ``continue``;` `      ``// Sort the string in``      ``// descending order``      ``char``[] myCharArr = st.ToCharArray();``      ``Array.Sort(myCharArr);``      ``string` `ns = ``""``;` `      ``for``(``int` `j = myCharArr.Length - 1; j >= 0; --j)``        ``ns += myCharArr[j];` `      ``// Update res``      ``res.Add(ns);``    ``}` `    ``// Print the array of strings``    ``printArray(res);``  ``}` `  ``// Driver Code` `  ``static` `public` `void` `Main ()``  ``{` `    ``string``[] arr = { ``"aaacbb"``, ``"geeks"``, ``"aaa"` `};``    ``int` `N = arr.Length;` `    ``sortedStrings(arr, N);` `  ``}``}` `// This code is contributed by avanitrachhadiya2155`

## Javascript

 ``

Output:

`cbb skgee`

Time Complexity: O(N * log N + M * log M), where M is the maximum length of a string in S[]
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up