Skip to content

Instantly share code, notes, and snippets.

@juanjunger
Created May 19, 2025 10:27
Show Gist options
  • Save juanjunger/eb0734ff15ab3ff61910038097a6fcdf to your computer and use it in GitHub Desktop.
Save juanjunger/eb0734ff15ab3ff61910038097a6fcdf to your computer and use it in GitHub Desktop.
/**
* @param {string} input
* @description Given a string, return the character that appears the most frequently based on the frequency of the characters.
* @returns {string}
*/
function main(input) {
if (!input || typeof input !== 'string') return '';
/*
* Count character frequencies
*
* Convert the input string into an object with the character as the key and the frequency as the value
* {
* a: 3,
* b: 2,
* c: 1,
* }
*/
const charCount = input.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
/*
* Find the maximum frequency of the characters
*/
const maxFreq = Math.max(...Object.values(charCount));
/*
* If max frequency is 1, return empty string
*/
if (maxFreq === 1) return ''; // handle "abc" or "" case
/*
* Collect all characters with max frequency
*/
const result = Object.entries(charCount)
.filter(([_, count]) => count === maxFreq)
.map(([char]) => char)
.join('');
return result;
}
// Test cases
console.log(main('aaabba')); // "a"
console.log(main('ccddcd')); // "cd"
console.log(main('abc')); // ""
console.log(main('efege')); // "e"
console.log(main('hihji')); // "hi"
console.log(main('')); // ""
console.log(main('klmmlk')); // "klm"
console.log(main('noonn')); // "n"
console.log(main('rrrtttrrrzzz')); // "r"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment