Skip to content

Instantly share code, notes, and snippets.

@marcobiedermann
Created August 16, 2022 07:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcobiedermann/e47afa4c18d13ab3b98f366139abefd7 to your computer and use it in GitHub Desktop.
Save marcobiedermann/e47afa4c18d13ab3b98f366139abefd7 to your computer and use it in GitHub Desktop.
Given a string, return the character that is most commonly used in the string.
function maxChar(str: string): string {
const map = new Map<string, number>();
let maxValue;
let maxCount = 0;
for (let char of str) {
const newCount = (map.get(char) || 0) + 1;
if (newCount > maxCount) {
maxValue = char;
maxCount = newCount;
}
map.set(char, newCount);
}
return maxValue;
}
maxChar("abcccccccd"); // c
maxChar("apple 1231111"); // 1
@SylviaMakuch
Copy link

SylviaMakuch commented Aug 18, 2022

JS Edition:

function maxChar(str) {
  const chars = {};
  let maxCount= 0;
  let maxChar = "";
  
  for(let char of str){
      chars[char] = chars[char] +1 ||1;
  }
  //this give an object 
  for (let key in chars){
      if (chars[key]  > maxCount) {
     maxCount = chars[key];
    maxChar = key;
      }
  }
  return maxChar;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment