Generate a Number in Decreasing order of Frequencies of characters of a given String
Given a string Str of length N, consisting of lowercase alphabets, the task is to generate a number in decreasing order of the frequency of characters in the given string. If two characters have the same frequency, the character with a smaller ASCII value appears first. Numbers assigned to characters {a, b, …., y, z} are {1, 2, …., 25, 26} respectively.
Note: For characters having values greater than 9 assigned to them, take its modulo 10.
Examples:
Input: N = 6, Str = “aaabbd”
Output: 124
Explanation:
Given characters and their respective frequencies are:
Since the number needs to be generated in increasing order of their frequencies, the final generated number is 124.
Input: N = 6, Str = “akkzzz”
Output: 611
Explanation:
Given characters and their respective frequencies are:
For z, value to assigned = 26
Hence, the corresponding digit assigned = 26 % 10 = 6
For k, value to assigned = 11
Hence, the corresponding digit assigned = 11 % 10 = 1
Since the number needs to be generated in increasing order of their frequencies, the final generated number is 611.
Approach:
Follow the steps below to solve the problem:
- Initialize a Map and store the frequencies of each character.
- Traverse the Map and insert all {Character, Frequency} pairs in a vector of pair.
- Sort this vector in a way such that the pair with higher frequency appears first and among pairs having the same frequency, those with smaller ASCII value come first.
- Traverse this vector and find the digit corresponding to each character.
- Print the final number generated.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool comp(pair< char , int >& p1,
pair< char , int >& p2)
{
if (p1.second == p2.second)
return p1.first < p2.first;
return p1.second > p2.second;
}
string sort(map< char , int >& m)
{
vector<pair< char , int > > a;
string out;
for ( auto x : m) {
a.push_back({ x.first, x.second });
}
sort(a.begin(), a.end(), comp);
for ( auto x : a) {
int k = x.first - 'a' + 1;
k = k % 10;
out = out + to_string(k);
}
return out;
}
string formString(string s)
{
map< char , int > mp;
for ( int i = 0; i < s.length(); i++)
mp[s[i]]++;
string res = sort(mp);
return res;
}
int main()
{
int N = 4;
string Str = "akkzzz" ;
cout << formString(Str);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FormString {
static class Pair implements Comparable<Pair> {
char first;
int second;
Pair( char first, int second) {
this .first = first;
this .second = second;
}
@Override
public int compareTo(Pair o) {
if ( this .second == o.second) {
return this .first - o.first;
}
return o.second - this .second;
}
}
static String sort(Map<Character, Integer> map) {
List<Pair> list = new ArrayList<>();
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
list.add( new Pair(entry.getKey(), entry.getValue()));
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
for (Pair pair : list) {
int k = (pair.first - 'a' + 1 ) % 10 ;
sb.append(k);
}
return sb.toString();
}
static String formString(String s) {
Map<Character, Integer> map = new HashMap<>();
for ( int i = 0 ; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0 ) + 1 );
}
return sort(map);
}
public static void main(String[] args) {
String Str = "akkzzz" ;
System.out.println(formString(Str));
}
}
|
Python3
def sort(m):
a = {}
out = ""
for x in m:
a[x] = []
a[x].append(m[x])
a = dict ( sorted (a.items(),
key = lambda x : x[ 0 ]))
a = dict ( sorted (a.items(),
reverse = True ,
key = lambda x : x[ 1 ]))
for x in a:
k = ord (x[ 0 ]) - ord ( 'a' ) + 1
k = k % 10
out = out + str (k)
return out
def formString(s):
mp = {}
for i in range ( len (s)):
if s[i] in mp:
mp[s[i]] + = 1
else :
mp[s[i]] = 1
res = sort(mp)
return res
N = 4
Str = "akkzzz"
print (formString( Str ))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static string SortDictionary(Dictionary< char , int > dict)
{
Dictionary< char , int > sortedDict = new Dictionary< char , int >();
foreach ( var pair in dict)
{
sortedDict.Add(pair.Key, pair.Value);
}
sortedDict = sortedDict.OrderByDescending(pair => pair.Value)
.ThenBy(pair => pair.Key)
.ToDictionary(pair => pair.Key, pair => pair.Value);
string output = "" ;
foreach ( var pair in sortedDict)
{
int k = (pair.Key - 'a' + 1) % 10;
output += k.ToString();
}
return output;
}
static string GetFormedString( string str)
{
Dictionary< char , int > freq = new Dictionary< char , int >();
foreach ( char c in str)
{
if (freq.ContainsKey(c))
{
freq++;
}
else
{
freq.Add(c, 1);
}
}
string formedStr = SortDictionary(freq);
return formedStr;
}
public static void Main( string [] args)
{
string str = "akkzzz" ;
Console.WriteLine(GetFormedString(str));
}
}
|
Javascript
<script>
function comp(p1,p2)
{
if (p1[1] == p2[1])
return p2.charCodeAt(0) - p1.charCodeAt(0);
return p2[1] - p1[1];
}
function sort(m)
{
let a = [];
let out= "" ;
for (let [x,y] of m) {
a.push([ x, y ]);
}
a.sort(comp);
for (let x of a) {
let k = (x[0].charCodeAt(0) - 97 + 1)%10;
out += k.toString();
}
return out;
}
function formString(s)
{
let mp = new Map();
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);
}
}
let res = sort(mp);
return res;
}
let N = 4;
let Str = "akkzzz" ;
document.write(formString(Str), "</br>" );
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Approach 2:
- Initialize an array count of size 26 to store the frequency of each character in the string.
- Traverse the string and update the frequency count of each character in the array.
- Traverse the count array and create a vector of pairs where each pair consists of a character and its frequency.
- Sort the vector of pairs in decreasing order of frequency. For pairs with the same frequency, sort them in increasing order of ASCII value.
- Traverse the sorted vector and generate the digit corresponding to each character. Append each digit to the result string.
- Return the result string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string formString(string s) {
int count[26] = {0};
for ( int i = 0; i < s.length(); i++) {
count[s[i] - 'a' ]++;
}
vector<pair< char , int >> v;
for ( int i = 0; i < 26; i++) {
if (count[i] > 0) {
v.push_back(make_pair( 'a' + i, count[i]));
}
}
sort(v.begin(), v.end(), [](pair< char , int >& p1, pair< char , int >& p2) {
if (p1.second == p2.second) {
return p1.first < p2.first;
}
return p1.second > p2.second;
});
string res;
for ( auto & p : v) {
int digit = (p.first - 'a' + 1) % 10;
res += to_string(digit);
}
return res;
}
int main() {
int N = 6;
string Str = "akkzzz" ;
cout << formString(Str);
return 0;
}
|
Java
import java.util.*;
public class Main {
static class Pair<K, V> {
public K key;
public V value;
public Pair(K key, V value) {
this .key = key;
this .value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public static String formString(String s) {
int [] count = new int [ 26 ];
for ( int i = 0 ; i < s.length(); i++) {
count[s.charAt(i) - 'a' ]++;
}
List<Pair<Character, Integer>> v = new ArrayList<>();
for ( int i = 0 ; i < 26 ; i++) {
if (count[i] > 0 ) {
v.add( new Pair<>(( char )( 'a' + i), count[i]));
}
}
Collections.sort(v, new Comparator<Pair<Character, Integer>>() {
@Override
public int compare(Pair<Character, Integer> p1, Pair<Character, Integer> p2) {
if (p1.getValue().equals(p2.getValue())) {
return Character.compare(p1.getKey(), p2.getKey());
}
return Integer.compare(p2.getValue(), p1.getValue());
}
});
StringBuilder res = new StringBuilder();
for (Pair<Character, Integer> p : v) {
int digit = (p.getKey() - 'a' + 1 ) % 10 ;
res.append(digit);
}
return res.toString();
}
public static void main(String[] args) {
int N = 6 ;
String Str = "akkzzz" ;
System.out.println(formString(Str));
}
}
|
Python3
def form_string(s):
count = [ 0 ] * 26
for i in range ( len (s)):
count[ ord (s[i]) - ord ( 'a' )] + = 1
v = []
for i in range ( 26 ):
if count[i] > 0 :
v.append(( chr (i + ord ( 'a' )), count[i]))
v.sort(key = lambda x: ( - x[ 1 ], x[ 0 ]))
res = ""
for p in v:
digit = ( ord (p[ 0 ]) - ord ( 'a' ) + 1 ) % 10
res + = str (digit)
return res
s = "akkzzz"
print (form_string(s))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string FormString( string s)
{
int [] count = new int [26];
foreach ( char c in s)
{
count++;
}
List<Tuple< char , int >> tuples = new List<Tuple< char , int >>();
for ( int i = 0; i < 26; i++)
{
if (count[i] > 0)
{
tuples.Add(Tuple.Create(( char )( 'a' + i), count[i]));
}
}
tuples.Sort((t1, t2) =>
{
if (t1.Item2 == t2.Item2)
{
return t1.Item1.CompareTo(t2.Item1);
}
return t2.Item2.CompareTo(t1.Item2);
});
string result = string .Concat(tuples.Select(t =>
{
int digit = (t.Item1 - 'a' + 1) % 10;
return digit.ToString();
}));
return result;
}
static void Main()
{
string str = "akkzzz" ;
Console.WriteLine(FormString(str));
}
}
|
Javascript
function formString(s) {
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 97]++;
}
const v = [];
for (let i = 0; i < 26; i++) {
if (count[i] > 0) {
v.push([String.fromCharCode(i + 97), count[i]]);
}
}
v.sort((p1, p2) => {
if (p1[1] === p2[1]) {
return p1[0].localeCompare(p2[0]);
}
return p2[1] - p1[1];
});
let res = '' ;
for (let i = 0; i < v.length; i++) {
const digit = (v[i][0].charCodeAt(0) - 97 + 1) % 10;
res += digit.toString();
}
return res;
}
const N = 6;
const Str = 'akkzzz' ;
console.log(formString(Str));
|
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Last Updated :
30 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...