This content originally appeared on DEV Community and was authored by Natalie Taktachev
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 = ''
}
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
}
}
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
}
}
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
}
This content originally appeared on DEV Community and was authored by Natalie Taktachev
Natalie Taktachev | Sciencx (2021-11-28T21:30:56+00:00) JavaScript MaxChar Algorithm. Retrieved from https://www.scien.cx/2021/11/28/javascript-maxchar-algorithm/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.