Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmModify string by sorting characters after removal of characters whose frequency is...

Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2

Given a string S consisting of N lowercase alphabets, the task is to remove the characters from the string whose frequency is not a power of 2 and then sort the string in ascending order.

Examples:

Input: S = “aaacbb”
Output: bbc
Explanation: The frequencies of ‘a’, ‘b’, and ‘c’ in the given string are 3, 2, 1. Only the character ‘a’ has frequency (= 3) which is not a power of 2. Therefore, removing ‘a’ from the string S modifies it to “cbb”. Therefore, the modified string after sorting is “bbc”.

Input: S = “neveropen”
Output: eeeefggkkorss

Approach: The given problem can be solved by using Hashing. Follow the steps below to solve the given problem:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove all the characters
// from a string that whose frequencies
// are not equal to a perfect power of 2
void countFrequency(string S, int N)
{
    // Stores the frequency of
    // each character in S
    int freq[26] = { 0 };
 
    // Iterate over characters of string
    for (int i = 0; i < N; i++) {
 
        // Update frequency of current
        // character in the array freq[]
        freq[S[i] - 'a']++;
    }
 
    // Traverse the array freq[]
    for (int i = 0; i < 26; i++) {
 
        // Check if the i-th letter
        // is absent from string S
        if (freq[i] == 0)
            continue;
 
        // Calculate log of frequency
        // of the current character
        // in the string S
        int lg = log2(freq[i]);
 
        // Calculate power of 2 of lg
        int a = pow(2, lg);
 
        // Check if freq[i]
        // is a power of 2
        if (a == freq[i]) {
 
            // Print letter i + 'a'
            // freq[i] times
            while (freq[i]--)
                cout << (char)(i + 'a');
        }
    }
}
 
// Driver Code
int main()
{
    string S = "aaacbb";
    int N = S.size();
    countFrequency(S, N);
 
    return 0;
}


Java




// Java program for the above approach
class GFG{
  
// Function to remove all the characters
// from a string that whose frequencies
// are not equal to a perfect power of 2
static void countFrequency(String S, int N)
{
     
    // Stores the frequency of
    // each character in S
    int []freq = new int[26];
    //Array.Clear(freq, 0, freq.Length);
 
    // Iterate over characters of string
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of current
        // character in the array freq[]
        freq[(int)S.charAt(i) - 'a'] += 1;
    }
 
    // Traverse the array freq[]
    for(int i = 0; i < 26; i++)
    {
         
        // Check if the i-th letter
        // is absent from string S
        if (freq[i] == 0)
            continue;
 
        // Calculate log of frequency
        // of the current character
        // in the string S
        int lg = (int)(Math.log(freq[i]) / Math.log(2));
 
        // Calculate power of 2 of lg
        int a = (int)Math.pow(2, lg);
 
        // Check if freq[i]
        // is a power of 2
        if (a == freq[i])
        {
             
            // Print letter i + 'a'
            // freq[i] times
            while (freq[i] > 0)
            {
                freq[i] -= 1;
                System.out.print((char)(i + 'a'));
            }
        }
    }
}
 
// Driver Code
public static void main(String args[])
{
    String S = "aaacbb";
    int N = S.length();
     
    countFrequency(S, N);
}
}
 
// This code is contributed by AnkThon


Python3




# Python3 program for the above approach
from math import log2
 
# Function to remove all the characters
# from a that whose frequencies are not
# equal to a perfect power of 2
def countFrequency(S, N):
     
    # Stores the frequency of
    # each character in S
    freq = [0] * 26
 
    # Iterate over characters of string
    for i in range(N):
         
        # Update frequency of current
        # character in the array freq[]
        freq[ord(S[i]) - ord('a')] += 1
 
    # Traverse the array freq[]
    for i in range(26):
 
        # Check if the i-th letter
        # is absent from S
        if (freq[i] == 0):
            continue
 
        # Calculate log of frequency
        # of the current character
        # in the S
        lg = int(log2(freq[i]))
 
        # Calculate power of 2 of lg
        a = pow(2, lg)
 
        # Check if freq[i]
        # is a power of 2
        if (a == freq[i]):
 
            # Print letter i + 'a'
            # freq[i] times
            while (freq[i]):
                print(chr(i + ord('a')), end = "")
                freq[i] -= 1
 
# Driver Code
if __name__ == '__main__':
     
    S = "aaacbb"
    N = len(S)
     
    countFrequency(S, N)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to remove all the characters
// from a string that whose frequencies
// are not equal to a perfect power of 2
static void countFrequency(string S, int N)
{
     
    // Stores the frequency of
    // each character in S
    int []freq = new int[26];
    Array.Clear(freq, 0, freq.Length);
 
    // Iterate over characters of string
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of current
        // character in the array freq[]
        freq[(int)S[i] - 'a'] += 1;
    }
 
    // Traverse the array freq[]
    for(int i = 0; i < 26; i++)
    {
         
        // Check if the i-th letter
        // is absent from string S
        if (freq[i] == 0)
            continue;
 
        // Calculate log of frequency
        // of the current character
        // in the string S
        int lg = (int)Math.Log((double)freq[i], 2.0);
 
        // Calculate power of 2 of lg
        int a = (int)Math.Pow(2, lg);
 
        // Check if freq[i]
        // is a power of 2
        if (a == freq[i])
        {
             
            // Print letter i + 'a'
            // freq[i] times
            while (freq[i] > 0)
            {
                freq[i] -= 1;
                Console.Write((char)(i + 'a'));
            }
        }
    }
}
 
// Driver Code
public static void Main()
{
    string S = "aaacbb";
    int N = S.Length;
     
    countFrequency(S, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript




<script>
      // JavaScript program for the above approach
      // Function to remove all the characters
      // from a string that whose frequencies
      // are not equal to a perfect power of 2
      function countFrequency(S, N)
      {
       
        // Stores the frequency of
        // each character in S
        var freq = new Array(26).fill(0);
 
        // Iterate over characters of string
        for (var i = 0; i < N; i++)
        {
         
          // Update frequency of current
          // character in the array freq[]
          freq[S[i].charCodeAt(0) - "a".charCodeAt(0)]++;
        }
 
        // Traverse the array freq[]
        for (var i = 0; i < 26; i++)
        {
         
          // Check if the i-th letter
          // is absent from string S
          if (freq[i] === 0) continue;
 
          // Calculate log of frequency
          // of the current character
          // in the string S
          var lg = parseInt(Math.log2(freq[i]));
 
          // Calculate power of 2 of lg
          var a = Math.pow(2, lg);
 
          // Check if freq[i]
          // is a power of 2
          if (a === freq[i])
          {
           
            // Print letter i + 'a'
            // freq[i] times
            while (freq[i]--)
              document.write(String.fromCharCode(i + "a".charCodeAt(0)));
          }
        }
      }
 
      // Driver Code
      var S = "aaacbb";
      var N = S.length;
      countFrequency(S, N);
       
      // This code is contributed by rdtank.
    </script>


Output: 

bbc

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
21 Jun, 2022
Like Article
Save Article


Previous


Next


Share your thoughts in the comments

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments