Print characters in decreasing order of frequency
Last Updated :
31 Mar, 2023
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 = “geeksforgeeks”
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
#include <bits/stdc++.h>
using namespace std;
void printChar(string str, int len)
{
unordered_map< char , int > occ;
for ( int i = 0; i < len; i++)
occ[str[i]]++;
int size = occ.size();
unordered_map< char , int >::iterator it;
while (size--) {
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;
}
}
cout << arg_max << " - " << currentMax << endl;
occ.erase(arg_max);
}
}
int main()
{
string str = "geeksforgeeks" ;
int len = str.length();
printChar(str, len);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printChar( char []arr, int len)
{
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 );
}
int size = occ.size();
while (size-- > 0 )
{
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();
}
}
System.out.print(arg_max + " - " +
currentMax + "\n" );
occ.remove(arg_max);
}
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.length();
printChar(str.toCharArray(), len);
}
}
|
Python3
def printChar(arr, Len ):
occ = {}
for i in range ( Len ):
if (arr[i] in occ):
occ[arr[i]] = occ[arr[i]] + 1
else :
occ[arr[i]] = 1
size = len (occ)
while (size > 0 ):
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 (f "{arg_max} - {currentMax}" )
occ.pop(arg_max)
size - = 1
Str = "geeksforgeeks"
Len = len ( Str )
printChar( list ( Str ), Len )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printChar( char []arr, int len)
{
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);
}
int size = occ.Count;
while (size-- > 0)
{
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;
}
}
Console.Write(arg_max + " - " +
currentMax + "\n" );
occ.Remove(arg_max);
}
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
int len = str.Length;
printChar(str.ToCharArray(), len);
}
}
|
Javascript
<script>
function printChar(arr, len)
{
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);
}
let size = occ.size;
while (size-- > 0)
{
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;
}
}
document.write(arg_max + " - " +
currentMax + "<br>" );
occ. delete (arg_max);
}
}
let str = "geeksforgeeks" ;
let len = str.length;
printChar(str.split( "" ), len);
</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;
void printChar(string str){
vector< char > arr[str.length() + 1];
for ( int i = 0; i <= str.length(); i++) {
vector< char > temp;
arr[i] = temp;
}
int freq[256] = { 0 };
for ( char c : str) {
freq[( int )c]++;
}
for ( int i = 0; i < 256; i++) {
if (freq[i] > 0) {
arr[freq[i]].insert(arr[freq[i]].begin(), ( char )(i));
}
}
for ( int i = str.length(); i >= 0; i--) {
if (arr[i].size() > 0) {
for ( char ch : arr[i]){
cout << ch << "-" << i << endl;
}
}
}
}
int main() {
string str = "geeksforgeeks" ;
printChar(str);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
printChar(str);
}
@SuppressWarnings ( "unchecked" )
public static void printChar(String str)
{
List<Character>[] arr = new List[str.length() + 1 ];
for ( int i = 0 ; i <= str.length(); i++) {
arr[i] = new ArrayList<>();
}
int [] freq = new int [ 256 ];
for ( int i = 0 ; i < str.length(); i++) {
freq[( char )str.charAt(i)]++;
}
for ( int i = 0 ; i < 256 ; i++) {
if (freq[i] > 0 ) {
arr[freq[i]].add( 0 , ( char )(i));
}
}
for ( int i = arr.length - 1 ; i >= 0 ; i--) {
if (!arr[i].isEmpty()) {
for ( char ch : arr[i]) {
System.out.println(ch + "-" + i);
}
}
}
}
}
|
Python3
from typing import List
def printChar(string: str ) - > None :
arr: List [ List [ str ]] = [[] for _ in range ( len (string) + 1 )]
freq = [ 0 ] * 256
for i in range ( len (string)):
freq[ ord (string[i])] + = 1
for i in range ( 256 ):
if freq[i] > 0 :
arr[freq[i]].insert( 0 , chr (i))
for i in range ( len (arr) - 1 , - 1 , - 1 ):
if arr[i]:
for ch in arr[i]:
print (f "{ch}-{i}" )
if __name__ = = "__main__" :
str = "geeksforgeeks"
printChar( str )
|
Javascript
function printChar(string) {
const arr = Array.from({ length: string.length + 1 }, () => []);
const freq = new Array(256).fill(0);
for (let i = 0; i < string.length; i++) {
freq[string.charCodeAt(i)] += 1;
}
for (let i = 0; i < 256; i++) {
if (freq[i] > 0) {
arr[freq[i]].unshift(String.fromCharCode(i));
}
}
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i].length > 0) {
arr[i].forEach((ch) => console.log(`${ch}-${i}`));
}
}
}
const str = "geeksforgeeks" ;
printChar(str);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void Main( string [] args) {
string str = "geeksforgeeks" ;
PrintChar(str);
}
public static void PrintChar( string str)
{
List< char >[] arr = new List< char >[str.Length + 1];
for ( int i = 0; i <= str.Length; i++)
{
arr[i] = new List< char >();
}
int [] freq = new int [256];
foreach ( char c in str) {
freq[( int )c]++;
}
for ( int i = 0; i < 256; i++) {
if (freq[i] > 0)
{
arr[freq[i]].Insert(0, ( char )(i));
}
}
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)
Share your thoughts in the comments
Please Login to comment...