Print the frequency of each character in Alphabetical order
Given a string str, the task is to print the frequency of each of the characters of str in alphabetical order.
Example:
Input: str = “aabccccddd”
Output: a2b1c4d3
Since it is already in alphabetical order, the frequency
of the characters is returned for each character.
Input: str = “geeksforgeeks”
Output: e4f1g2k2o1r1s2
Approach:
- Create a Map to store the frequency of each of the characters of the given string.
- Iterate through the string and check if the character is present in the map.
- If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1.
- Finally, print the frequency of each of the character in alphabetical order.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; const int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order void compressString(string s, int n) { // To store the frequency // of the characters int freq[MAX] = { 0 }; // Update the frequency array for ( int i = 0; i < n; i++) { freq[s[i] - 'a' ]++; } // Print the frequency in alphatecial order for ( int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue ; cout << ( char )(i + 'a' ) << freq[i]; } } // Driver code int main() { string s = "geeksforgeeks" ; int n = s.length(); compressString(s, n); return 0; } |
Java
// Java implementation of the approach class GFG { static int MAX = 26 ; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString(String s, int n) { // To store the frequency // of the characters int freq[] = new int [MAX] ; // Update the frequency array for ( int i = 0 ; i < n; i++) { freq[s.charAt(i) - 'a' ]++; } // Print the frequency in alphatecial order for ( int i = 0 ; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0 ) continue ; System.out.print(( char )(i + 'a' ) + "" + freq[i]); } } // Driver code public static void main (String[] args) { String s = "geeksforgeeks" ; int n = s.length(); compressString(s, n); } } // This code is contributed by AnkitRai01 |
Python3
# Python3 implementation of the approach MAX = 26 ; # Function to print the frequency # of each of the characters of # s in alphabetical order def compressString(s, n) : # To store the frequency # of the characters freq = [ 0 ] * MAX ; # Update the frequency array for i in range (n) : freq[ ord (s[i]) - ord ( 'a' )] + = 1 ; # Print the frequency in alphatecial order for i in range ( MAX ) : # If the current alphabet doesn't # appear in the string if (freq[i] = = 0 ) : continue ; print (( chr )(i + ord ( 'a' )),freq[i],end = " " ); # Driver code if __name__ = = "__main__" : s = "geeksforgeeks" ; n = len (s); compressString(s, n); # This code is contributed by AnkitRai01 |
C#
// C# implementation of the approach using System; class GFG { static int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString( string s, int n) { // To store the frequency // of the characters int []freq = new int [MAX] ; // Update the frequency array for ( int i = 0; i < n; i++) { freq[s[i] - 'a' ]++; } // Print the frequency in alphatecial order for ( int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue ; Console.Write(( char )(i + 'a' ) + "" + freq[i]); } } // Driver code public static void Main() { string s = "geeksforgeeks" ; int n = s.Length; compressString(s, n); } } // This code is contributed by AnkitRai01 |
Javascript
<script> // Javascript implementation of the approach let MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order function compressString(s, n) { // To store the frequency // of the characters let freq = new Array(MAX); freq.fill(0); // Update the frequency array for (let i = 0; i < n; i++) { freq[s[i].charCodeAt() - 'a' .charCodeAt()]++; } // Print the frequency in alphatecial order for (let i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue ; document.write(String.fromCharCode(i + 'a'.charCodeAt()) + "" + freq[i]); } } let s = "geeksforgeeks" ; let n = s.length; compressString(s, n); </script> |
Output:
e4f1g2k2o1r1s2
Time Complexity: O(n)
Auxiliary Space: O(1)
Using Map(stl):-
The Approach:
The approach is very simple we are go on traversing and print the all the char with there frequency.
C++
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { //given string. string s = "geeksforgeeks" ; //map char-int pair. map< char , int >mp; //map over string. for ( auto it:s)mp[it]++; //printing the char with there frequency. cout<< "All character in string with there frequency :" <<endl; for ( auto it:mp)cout<<it.first<<it.second; return 0; } |
Python3
# Python program for the above approach s = "geeksforgeeks" # map of char-int pair mp = {} # map over string for i in range ( len (s)): if (mp.get(s[i]) ! = None ): mp[s[i]] = mp.get(s[i]) + 1 else : mp[s[i]] = 1 # printing the char with frequency myKeys = list (mp.keys()) myKeys.sort() mp = {i : mp[i] for i in myKeys} for i in mp: print (i, end = "") print (mp[i], end = "") |
C#
using System; using System.Collections.Generic; class GFG { static void Main( string [] args) { //given string. string s = "geeksforgeeks" ; //map char-int pair. Dictionary< char , int > mp = new Dictionary< char , int >(); //map over string. foreach ( char c in s) { if (mp.ContainsKey(c)) { mp++; } else { mp = 1; } } //printing the char with there frequency. Console.WriteLine( "All character in string with their frequency:" ); foreach (KeyValuePair< char , int > pair in mp) { Console.Write(pair.Key + "" + pair.Value); } } } // code by ksam24000 |
Javascript
// JavaScript program for above approach // given string let s = "geeksforgeeks" ; // map char-int pair let mp = new Map(); // map over string for (let i = 0; i<s.length; i++){ if (mp.has(s[i])){ mp.set(s[i], mp.get(s[i])+1); } else { mp.set(s[i], 1); } } // printing the cha with there frequency. console.log( "All characters in string with there frequency : " ); var unsortedArray = [ ...mp]; var sortedArray = unsortedArray.sort(([key1, value1], [key2, value2]) => key1.localeCompare(key2)) mp = new Map(sortedArray) mp.forEach( function (value, key){ console.log(key+value); }) // This code is contributed by Yash Agarwal(yashagarwal2852002) |
Java
import java.util.*; public class Main { public static void main(String[] args) { // given string String s = "geeksforgeeks" ; // map char-int pair Map<Character, Integer> mp = new HashMap<Character, Integer>(); // map over string for ( char c : s.toCharArray()) { if (mp.containsKey(c)) { mp.put(c, mp.get(c) + 1 ); } else { mp.put(c, 1 ); } } // printing the char with their frequency System.out.println( "All character in string with their frequency :" ); for (Map.Entry<Character, Integer> entry : mp.entrySet()) { System.out.print(entry.getKey() + "" + entry.getValue()); } } } // ksam24000 |
Output
All character in string with there frequency : e4f1g2k2o1r1s2
Complexity Analysis:
Time Complexity: O(n),for tarversing string.
Auxiliary Space: O(n),for map.
Approach 3: Recursive approach
Algorithm:
- Take the string “s” as input and calculate size in n.
- Run a loop from ‘a’ to ‘z’ and call the “compressString” function for each time with count = 0 to store the frequency of the letter.
- The “compressString” function check if counter i>size of the string then return the function else increment the count if character equal to s[i] and call the “compressString” again with i+1;
- Now check if count is not equal to 0 then print the letter with count.
C++
// C++ code for above approach #include <bits/stdc++.h> using namespace std; // Recursive function void compressString(string s, int n, int i, char letter, int &count) { // Base case: if i>size of string the return if (i>n-1) return ; // If the letter equal to the s[i] then increment count by 1 if (s[i]==letter) count++; // Call the recursive function again with i+1 compressString(s,n,i+1,letter,count); } // Driver code int main() { string s = "geeksforgeeks" ; // input string int n = s.length(); // size of string for ( char letter = 'a' ; letter<= 'z' ; letter++) { int count = 0; // frequency counter // Call the recursive function compressString(s,n,0,letter,count); if (count==0) // if count equal to 0 continue. continue ; cout<<letter<<count; // Print the letter with count. } return 0; } |
Java
import java.util.*; class Main { // Recursive function static void compressString(String s, int n, int i, char letter, int [] count) { // Base case: if i > size of string then return if (i > n - 1 ) { return ; } // If the letter is equal to s[i], then increment count by 1 if (s.charAt(i) == letter) { count[ 0 ]++; } // Call the recursive function again with i+1 compressString(s, n, i+ 1 , letter, count); } // Driver code public static void main(String[] args) { String s = "geeksforgeeks" ; // input string int n = s.length(); // size of string for ( char letter = 'a' ; letter <= 'z' ; letter++) { int [] count = { 0 }; // frequency counter // Call the recursive function compressString(s, n, 0 , letter, count); if (count[ 0 ] == 0 ) { // if count is equal to 0, continue continue ; } System.out.print(letter + "" + count[ 0 ]); // Print the letter with count. } } } |
C#
using System; class GFG { // Recursive function static void compressString( string s, int n, int i, char letter, ref int count) { // Base case: if i>size of string the return if (i > n - 1) return ; // If the letter equal to the s[i] then increment // count by 1 if (s[i] == letter) count++; // Call the recursive function again with i+1 compressString(s, n, i + 1, letter, ref count); } static void Main() { string s = "geeksforgeeks" ; // input string int n = s.Length; // size of string for ( char letter = 'a' ; letter <= 'z' ; letter++) { int count = 0; // Call the recursive function compressString(s, n, 0, letter, ref count); // if count equal to 0 continue. if (count == 0) continue ; // Print the letter with count. Console.Write(letter); Console.Write(count); } } } |
Python3
# Recursive function to compress a string def compressString(s, n, i, letter, count): # Base case: if i>size of string then return if i > n - 1 : return # If the letter is equal to the s[i], then increment count by 1 if s[i] = = letter: count + = 1 # Call the recursive function again with i+1 compressString(s, n, i + 1 , letter, count) return count # Driver code if __name__ = = '__main__' : s = "geeksforgeeks" # input string n = len (s) # size of string for letter in range ( ord ( 'a' ), ord ( 'z' ) + 1 ): letter = chr (letter) count = compressString(s, n, 0 , letter, 0 ) if count = = 0 : # if count equal to 0 continue continue print (letter, count, end = '') # Print the letter with count |
Javascript
// Recursive function function compressString(s, n, i, letter, count) { // Base case: if i > size of string then return if (i > n - 1) { return ; } // If the letter is equal to s[i], then increment count by 1 if (s.charAt(i) === letter) { count[0]++; } // Call the recursive function again with i+1 compressString(s, n, i + 1, letter, count); } // Driver code const s = "geeksforgeeks" ; // input string const n = s.length; // size of string ans = "" ; for (let letter = "a" ; letter <= "z" ; letter = String.fromCharCode(letter.charCodeAt(0) + 1)) { const count = [0]; // frequency counter // Call the recursive function compressString(s, n, 0, letter, count); if (count[0] === 0) { // if count is equal to 0, continue continue ; } ans = ans +letter + "" + count[0]; // Print the letter with count. } console.log(ans); |
Output
e4f1g2k2o1r1s2
Time Complexity: O(n)
Auxiliary Space: O(1)
Please Login to comment...