Write a program to check if all characters have equal number of occurrences
The problem:
Given a string s, return true if s is a good string, or false otherwise.
A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Example #1
Input: s = "abacbc" Output: true Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
Example #2
Input: s = "aaabb" Output: false Explanation: The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
The solution
const areOccurrencesEqual = (s) => { const freq = {}; for (let index = 0; index < s.length; index++) { const key = s.charCodeAt(index) - 97; freq[key] = freq[key] ? freq[key] + 1: 1; } const freqArr = Object.values(freq); if(freqArr.length < 2 ) { return true; } const firstFreq = freq[s.charCodeAt(0) - 97]; for (let i = 1; i < freqArr.length; i++) { if(freqArr[i] !== firstFreq) { return false; } } return true; }; const str = 'aabbccf'; console.log(areOccurrencesEqual(str)); // false