JavaScript Program to Check Equal Character Frequencies
Last Updated :
19 Jul, 2024
We have given a String to ensure it has equal character frequencies, if not, equate by adding required characters and printing the final string in the console.
Example:
Input: test_str = ‘geeksforgeeks’
Output: geeksforgeeksggkkssfffooorrr
Explanation: Maximum characters are 4 of ‘e’.
Other character are appended of frequency 4 – (count of chars).
Input: test_str = ‘geksforgeeks’
Output: geeksforgeeksggksffoorr
Explanation: Maximum characters are 3 of ‘e’.
Other character are appended of frequency 3 – (count of chars).
These are the following approaches by using these we can solve this question:
Using JavaScript map():
In this approach, we are checking for characters in a string with the highest frequency and adjusting the string to make all characters occur with the same frequency. It utilizes methods like split, repeat, and map to find and modify characters, ensuring their frequencies are equal. The final string 'res' is the original string with additional characters appended to match the maximum frequency.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing string
let test_str = 'abca';
// Printing original string
console.log("The original string is : " + test_str);
// Getting maximum frequency character
let max_freq = Math.max(...[...test_str]
.map((ele) => test_str.split(ele).length - 1));
// Equating frequencies
let res = test_str;
[...test_str].forEach((chr) => {
// If frequencies don't match max_freq
if (res.split(chr).length - 1 !== max_freq) {
res += chr.repeat(max_freq -
(test_str.split(chr).length - 1));
}
});
// Printing result
console.log("Equal character frequency String : " + res);
OutputThe original string is : abca
Equal character frequency String : abcabc
Using forEach() and reduce() method:
In this approach, we are finding character with the highest frequency in a string and ensures all characters appear with the same frequency. It uses the split and reduce methods to count character occurrences, and Math.max to find the maximum frequency. The code then adjusts the string to match the highest frequency, resulting in the modified string res.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing string
let test_str = 'abcaa';
// Printing original string
console.log("The original string is : " + test_str);
// Getting maximum frequency
// character using Counter equivalent
let freq_dict =
test_str.split('').reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
let max_freq = Math.max(...Object.values(freq_dict));
// Equating frequencies
let res = test_str;
[...test_str].forEach((chr) => {
// If frequencies don't match max_freq
if (res.split(chr).length - 1 !== max_freq) {
res += chr.repeat(max_freq
- (test_str.split(chr).length - 1));
}
});
// Printing result
console.log("Equal character frequency String : " + res);
OutputThe original string is : abcaa
Equal character frequency String : abcaabbcc
Using Object Properties
This approach counts character frequencies using an object and then counts these frequency values using another object. If the length of the frequency count object's keys is 1, it means all characters have equal frequencies.
Example: In this example the function hasEqualFrequencies checks if all characters in a string have the same frequency.
JavaScript
function hasEqualFrequencies(str) {
const freq = {};
for (const char of str) {
freq[char] = (freq[char] || 0) + 1;
}
const freqCount = {};
for (const count of Object.values(freq)) {
freqCount[count] = (freqCount[count] || 0) + 1;
}
return Object.keys(freqCount).length === 1;
}
console.log(hasEqualFrequencies("aabb"));
console.log(hasEqualFrequencies("aabc"));
Using Set
This approach iterates through the string and counts the frequency of each character using a Map. It keeps track of the maximum frequency encountered. Then, it uses a Set to check if all frequencies are the same. If the size of the Set is 1, it means all character frequencies are equal, and the function returns true, otherwise, it returns false.
Example:
JavaScript
// Function to check if all character frequencies are equal
function hasEqualFrequencies(str) {
const freqMap = new Map();
let maxFreq = 0;
// Count frequency of each character
for (const char of str) {
freqMap.set(char, (freqMap.get(char) || 0) + 1);
maxFreq = Math.max(maxFreq, freqMap.get(char));
}
// If all frequencies are the same, return true
// We use a Set to check if all frequencies are the same
return new Set(freqMap.values()).size === 1;
}
// Test the function
console.log(hasEqualFrequencies("aabb")); // true
console.log(hasEqualFrequencies("aabc")); // false
Using reduce() Method
This approach finds the character with the highest frequency and ensures all characters appear with the same frequency. The reduce() method is used to count character occurrences, and then the string is adjusted to match the highest frequency.
Example: In this example The hasEqualFrequencies function determines if all characters in the input string have equal frequencies. It counts character frequencies and then checks if all frequency values themselves have a uniform count, returning true for "aabb" and false for "aabc".
JavaScript
function hasEqualFrequencies(str) {
// Count the frequency of each character using reduce
const charCount = str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
// Count the frequency of the frequencies using reduce
const freqCount = Object.values(charCount).reduce((acc, count) => {
acc[count] = (acc[count] || 0) + 1;
return acc;
}, {});
// Check if all frequencies are the same
return Object.keys(freqCount).length === 1;
}
console.log(hasEqualFrequencies("aabb"));
console.log(hasEqualFrequencies("aabc"));
Using Array.prototype.reduce and Array.prototype.flatMap
In this approach, we will find the character with the highest frequency and ensure all characters in the string appear with the same frequency by adding the necessary characters.
Example: This example demonstrates how to use the reduce and flatMap methods to adjust character frequencies.
JavaScript
function equalizeFrequencies(str) {
// Count the frequency of each character
const freqMap = str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
const maxFreq = Math.max(...Object.values(freqMap));
const result = Object.entries(freqMap).flatMap(([char, count]) => {
return char.repeat(maxFreq - count);
}).join('');
return str + result;
}
let test_str = 'geeksforgeeks';
console.log("The original string is : " + test_str);
console.log("Equal character frequency String : " + equalizeFrequencies(test_str));
test_str = 'geksforgeeks';
console.log("The original string is : " + test_str);
console.log("Equal character frequency String : " + equalizeFrequencies(test_str));
OutputThe original string is : geeksforgeeks
Equal character frequency String : geeksforgeeksggkkssfffooorrr
The original string is : geksforgeeks
Equal character frequency String : geksforgeeksgksffoorr
Using Sorting and Grouping
This approach sorts the characters of the string, counts their frequencies, and then appends the necessary characters to ensure that all characters have the same frequency.
Example: This example demonstrates how to use sorting and grouping to adjust character frequencies.
JavaScript
function equalizeFrequencies(str) {
const sortedChars = str.split('').sort();
const freqMap = sortedChars.reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
const maxFreq = Math.max(...Object.values(freqMap));
let result = str;
for (let char in freqMap) {
const count = freqMap[char];
if (count < maxFreq) {
result += char.repeat(maxFreq - count);
}
}
return result;
}
let test_str = 'geeksforgeeks';
console.log("The original string is : " + test_str);
console.log("Equal character frequency String : " + equalizeFrequencies(test_str));
test_str = 'geksforgeeks';
console.log("The original string is : " + test_str);
console.log("Equal character frequency String : " + equalizeFrequencies(test_str));
OutputThe original string is : geeksforgeeks
Equal character frequency String : geeksforgeeksfffggkkooorrrss
The original string is : geksforgeeks
Equal character frequency String : geksforgeeksffgkoorrs
Similar Reads
JavaScript Program to Check if a Character is Vowel or Not
In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are âaâ, âeâ, âiâ, âoâ, and âuâ. All other characters are not vowels. Examples: Input : 'u'Output : TrueExplanation: 'u' is among the vowel characters family (a,e,i,o,u).Input : 'b'Output : Fal
4 min read
JavaScript Program to Check for Repeated Characters in a String
Here are the different methods to check for repeated characters in a string using JavaScript 1. Using a Frequency Counter (Object)A frequency counter is one of the most efficient ways to check for repeated characters in a string. This approach involves iterating over the string and counting how ofte
3 min read
JavaScript Program to Check if Kth Index Elements are Unique
In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console. Example: Input: test_list = [âgfgâ, âbestâ
6 min read
JavaScript Program to Count the Occurrences of Each Character
Here are the various methods to count the occurrences of each character Using JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values. [GFGTABS] JavaScript const count = (s) => { const obj = {}; f
4 min read
Least Frequent Character in String in JavaScript
In JavaScript, finding the least frequent character in a string involves identifying the character that occurs the fewest times within the given string by iterating through the string, counting the occurrences of each character, and determining the one with the minimum frequency. This algorithmic ta
2 min read
JavaScript - Frequency of characters in Alphabatic Order
The operation involves counting how many times each character in alphabetic characters in a given string. Using Object (Simple and Efficient for Small to Moderate Strings)Object in JavaScript allow storing key value pairs. So we use items as keys and their frequencies as values. [GFGTABS] JavaScript
2 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table
3 min read
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = âgeeksforgeeksâOutput:e, count = 4g, count = 2k, count = 2s, count = 2Ta
5 min read
JavaScript Program to Find Kâth Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
7 min read
JavaScript Program to Check if Two Strings are Same or Not
In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false. Examples: Input: str1 = Geeks, str2 = GeeksOutput: True. Strings are the SameInput: str1 = Geeks, str2 = GeekOutp
4 min read