DEV Community

stuxnat
stuxnat

Posted on

JavaScript MaxChar Algorithm

In my last few posts I've written about common interview questions I've come across. Today, another: MaxChar. This problem asks of a given string, to return the character that appears most frequently in the string.

To start, write a function that takes in a string, with a variable set to an empty string to keep track of the letter which appears the most. Another thing we will want to have is an object to keep track of all characters in a string, along with the number of times it appears:

function maxChar(string){
     let chars = {}
     let maxChar = ''
}
Enter fullscreen mode Exit fullscreen mode

The next thing to do is to iterate through the string using a for loop.

function maxChar(string){
     let chars = {}
     let maxChar = ''

     for (let char of string){
      let current = char 
  }
}

Enter fullscreen mode Exit fullscreen mode

Here, the char variable is used keep track of the current character in the iteration. Next, we'll want to increase the numerical value by 1 if the character is already included in the chars object. If it is not, it will be set to 1 if it is a new character.

function maxChar(string){
     let chars = {}
     let maxChar = ''

     for (let char of string){
      let current = char 
      char[current] = char[current] + 1 || 1 
  }
}
Enter fullscreen mode Exit fullscreen mode

The last step of this requires comparing current with maxChar to determine which one appears most often.

function maxChar(string){
     let chars = {}
     let maxChar = ''

     for (let char of string){
      let current = char 
      char[current] = char[current] + 1 || 1 
      if (maxChar === '' || chars[current] > chars[maxChar]) {
maxChar = current}
  }
return maxChar
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const maxChar = str => Object.entries([...str].reduce((a,i)=>({...a,[i]:~~a[i]+1}),{})).sort(([i,a],[l,b])=>b-a)[0][0]
Enter fullscreen mode Exit fullscreen mode

One liner version (although quite inefficient)