Print characters in decreasing order of frequency
Given string str, the task is to print the characters in decreasing order of their frequency. If the frequency of two characters is the same then sort them in descending order alphabetically.
Examples:
Input: str = “w3wiki”
Output:
e – 4
s – 2
k – 2
g – 2
r – 1
o – 1
f – 1
Input: str = “bbcc”
Output:
c – 2
b – 2
Approach 1:
- Use an unordered_map to store the frequencies of all the elements of the given string.
- Find the maximum frequency element from the map, print it with its frequency, and remove it from the map.
- Repeat the previous step while the map is not empty.
Below is the implementation of the above approach:
CPP
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to print the characters // of the given string in decreasing // order of their frequencies void printChar(string str, int len) { // To store the unordered_map< char , int > occ; for ( int i = 0; i < len; i++) occ[str[i]]++; // Map's size int size = occ.size(); unordered_map< char , int >::iterator it; // While there are elements in the map while (size--) { // Finding the maximum value // from the map unsigned currentMax = 0; char arg_max; for (it = occ.begin(); it != occ.end(); ++it) { if (it->second > currentMax || (it->second == currentMax && it->first > arg_max)) { arg_max = it->first; currentMax = it->second; } } // Print the character // alongwith its frequency cout << arg_max << " - " << currentMax << endl; // Delete the maximum value occ.erase(arg_max); } } // Driver code int main() { string str = "w3wiki" ; int len = str.length(); printChar(str, len); return 0; } |
Java
// Java implementation of the approach import java.util.*; class GFG{ // Function to print the characters // of the given String in decreasing // order of their frequencies static void printChar( char []arr, int len) { // To store the HashMap<Character, Integer> occ = new HashMap<Character, Integer>(); for ( int i = 0 ; i < len; i++) if (occ.containsKey(arr[i])) { occ.put(arr[i], occ.get(arr[i]) + 1 ); } else { occ.put(arr[i], 1 ); } // Map's size int size = occ.size(); // While there are elements in the map while (size-- > 0 ) { // Finding the maximum value // from the map int currentMax = 0 ; char arg_max = 0 ; for (Map.Entry<Character, Integer> it : occ.entrySet()) { if (it.getValue() > currentMax || (it.getValue() == currentMax && it.getKey() > arg_max)) { arg_max = it.getKey(); currentMax = it.getValue(); } } // Print the character // alongwith its frequency System.out.print(arg_max + " - " + currentMax + "\n" ); // Delete the maximum value occ.remove(arg_max); } } // Driver code public static void main(String[] args) { String str = "w3wiki" ; int len = str.length(); printChar(str.toCharArray(), len); } } // This code is contributed by gauravrajput1 |
Python3
# Python implementation of the approach # Function to print the characters # of the given String in decreasing # order of their frequencies def printChar(arr, Len ): # To store the occ = {} for i in range ( Len ): if (arr[i] in occ): occ[arr[i]] = occ[arr[i]] + 1 else : occ[arr[i]] = 1 # Map's size size = len (occ) # While there are elements in the map while (size > 0 ): # Finding the maximum value # from the map currentMax = 0 arg_max = 0 for key, value in occ.items(): if (value > currentMax or (value = = currentMax and key > arg_max)): arg_max = key currentMax = value # Print the character # alongwith its frequency print (f "{arg_max} - {currentMax}" ) # Delete the maximum value occ.pop(arg_max) size - = 1 # Driver code Str = "w3wiki" Len = len ( Str ) printChar( list ( Str ), Len ) # This code is contributed by shinjanpatra |
C#
// C# implementation of the approach using System; using System.Collections.Generic; class GFG{ // Function to print the characters // of the given String in decreasing // order of their frequencies static void printChar( char []arr, int len) { // To store the Dictionary< char , int > occ = new Dictionary< char , int >(); for ( int i = 0; i < len; i++) if (occ.ContainsKey(arr[i])) { occ[arr[i]] = occ[arr[i]] + 1; } else { occ.Add(arr[i], 1); } // Map's size int size = occ.Count; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map int currentMax = 0; char arg_max = ( char )0; foreach (KeyValuePair< char , int > it in occ) { if (it.Value > currentMax || (it.Value == currentMax && it.Key > arg_max)) { arg_max = it.Key; currentMax = it.Value; } } // Print the character // alongwith its frequency Console.Write(arg_max + " - " + currentMax + "\n" ); // Delete the maximum value occ.Remove(arg_max); } } // Driver code public static void Main(String[] args) { String str = "w3wiki" ; int len = str.Length; printChar(str.ToCharArray(), len); } } // This code is contributed by Princi Singh |
Javascript
<script> // Javascript implementation of the approach // Function to print the characters // of the given String in decreasing // order of their frequencies function printChar(arr, len) { // To store the let occ = new Map(); for (let i = 0; i < len; i++) if (occ.has(arr[i])) { occ.set(arr[i], occ.get(arr[i]) + 1); } else { occ.set(arr[i], 1); } // Map's size let size = occ.size; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map let currentMax = 0; let arg_max = 0; for (let [key, value] of occ.entries()) { if (value > currentMax || (value == currentMax && key > arg_max)) { arg_max = key; currentMax = value; } } // Print the character // alongwith its frequency document.write(arg_max + " - " + currentMax + "<br>" ); // Delete the maximum value occ. delete (arg_max); } } // Driver code let str = "w3wiki" ; let len = str.length; printChar(str.split( "" ), len); // This code is contributed by patel2127 </script> |
Output
e - 4 s - 2 k - 2 g - 2 r - 1 o - 1 f - 1
Approach 2 : We will make an array arr of size one more than the size of given string length in which we will store List of characters whose frequency is equal to the index of arr and follow the below steps :
- Make a frequency map using array of characters present in the given string.
- Traverse frequency array, if its value is greater than zero let say k.
- On kth index of arr store it’s character value in List at index 0(As we need descending order of alphabets if frequency is same).
- Traverse arr from backwards as we need greater frequency first if List at that index is not empty then print its frequency and character.
Implementation of above approach :
C++
#include <bits/stdc++.h> using namespace std; // Function to print the characters // of the given string in decreasing // order of their frequencies void printChar(string str){ // Initializing vector of vector type. vector< char > arr[str.length() + 1]; for ( int i = 0; i <= str.length(); i++) { // Initializing vector of type char. vector< char > temp; arr[i] = temp; } int freq[256] = { 0 }; // Mapping frequency map for ( char c : str) { freq[( int )c]++; } // Traversing frequency array for ( int i = 0; i < 256; i++) { if (freq[i] > 0) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].insert(arr[freq[i]].begin(), ( char )(i)); } } // Traversing arr from backwards as we need greater // frequency character first for ( int i = str.length(); i >= 0; i--) { if (arr[i].size() > 0) { for ( char ch : arr[i]){ cout << ch << "-" << i << endl; } } } } // Driver Code int main() { string str = "w3wiki" ; printChar(str); return 0; } |
Java
// Java implementation of above approach import java.util.*; class GFG { // Driver Code public static void main(String[] args) { String str = "w3wiki" ; printChar(str); } @SuppressWarnings ( "unchecked" ) // Function to print the characters // of the given string in decreasing // order of their frequencies public static void printChar(String str) { // Initializing array of List type. List<Character>[] arr = new List[str.length() + 1 ]; for ( int i = 0 ; i <= str.length(); i++) { // Initializing List of type Character. arr[i] = new ArrayList<>(); } int [] freq = new int [ 256 ]; // Mapking frequency map for ( int i = 0 ; i < str.length(); i++) { freq[( char )str.charAt(i)]++; } // Traversing frequency array for ( int i = 0 ; i < 256 ; i++) { if (freq[i] > 0 ) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].add( 0 , ( char )(i)); } } // Traversing arr from backwards as we need greater // frequency character first for ( int i = arr.length - 1 ; i >= 0 ; i--) { if (!arr[i].isEmpty()) { for ( char ch : arr[i]) { System.out.println(ch + "-" + i); } } } } } |
Python3
# Python implementation of above approach from typing import List def printChar(string: str ) - > None : # Initializing array of List type arr: List [ List [ str ]] = [[] for _ in range ( len (string) + 1 )] freq = [ 0 ] * 256 # Mapking frequency map for i in range ( len (string)): freq[ ord (string[i])] + = 1 # Traversing frequency array for i in range ( 256 ): if freq[i] > 0 : # If frequency array is greater than zero # then storing its character on # i-th(frequency of that character) index # of arr arr[freq[i]].insert( 0 , chr (i)) # Traversing arr from backwards as we need greater # frequency character first for i in range ( len (arr) - 1 , - 1 , - 1 ): if arr[i]: for ch in arr[i]: print (f "{ch}-{i}" ) # Driver Code if __name__ = = "__main__" : str = "w3wiki" printChar( str ) # This code is contributed by codebraxnzt |
Javascript
function printChar(string) { // Initializing array of List type const arr = Array.from({ length: string.length + 1 }, () => []); const freq = new Array(256).fill(0); // Mapping frequency map for (let i = 0; i < string.length; i++) { freq[string.charCodeAt(i)] += 1; } // Traversing frequency array for (let i = 0; i < 256; i++) { if (freq[i] > 0) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].unshift(String.fromCharCode(i)); } } // Traversing arr from backwards as we need greater // frequency character first for (let i = arr.length - 1; i >= 0; i--) { if (arr[i].length > 0) { arr[i].forEach((ch) => console.log(`${ch}-${i}`)); } } } // Driver Code const str = "w3wiki" ; printChar(str); |
C#
using System; using System.Collections.Generic; class GFG { // Driver Code public static void Main( string [] args) { string str = "w3wiki" ; PrintChar(str); } // Function to print the characters // of the given string in decreasing // order of their frequencies public static void PrintChar( string str) { // Initializing array of List type. List< char >[] arr = new List< char >[str.Length + 1]; for ( int i = 0; i <= str.Length; i++) { // Initializing List of type char. arr[i] = new List< char >(); } int [] freq = new int [256]; // Mapping frequency map foreach ( char c in str) { freq[( int )c]++; } // Traversing frequency array for ( int i = 0; i < 256; i++) { if (freq[i] > 0) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].Insert(0, ( char )(i)); } } // Traversing arr from backwards as we need greater // frequency character first for ( int i = arr.Length - 1; i >= 0; i--) { if (arr[i].Count > 0) { foreach ( char ch in arr[i]) { Console.WriteLine(ch + "-" + i); } } } } } |
Output
e-4 s-2 k-2 g-2 r-1 o-1 f-1
Time Complexity : O(n), n is the length of given string
Auxiliary Space : O(n)