Max Chars Problem
Return the character that is most commonly used in the given string
Given a string, return the character that is most commonly used
maxChar('abcccccccccccd') // === 'c'
maxChar('apple 123111111')// === '1'
Solution 1 - For loops
Creating the object
- Create an empty object variable
- Loop Through each character in the string
- Check if the character is in the object variable
- If not in the object add it with a value of 1, if its already there plus the value by 1
We will now have a object that looks similar to the below:
chars = {
"a":1,
"b":1,
"c":11,
"d":1,
}
Now we need to loop through the object to get the max value and return the Key
- Set 2 new variables. A empty string (maxChar) and a integer starting at 0 (max)
- Loop through the object variable
- Check if the current chars value is higher then the integer value (max)
- If the number is greater, set the integer variable (max) to this value and set the string variable (maxChar) to the current char in the for loop
- Return the string variable
const maxChar = (str) => {
const chars = {}
let max = 0
let maxChar = ''
for (let char of str) {
if (chars[char]) {
chars[char]++
} else {
chars[char] = 1
}
}
for (let char in chars) {
if (chars[char] > max) {
max = chars[char]
maxChar = char
}
}
return maxChar
}
Solution 2 - forEach & reduce
- Create an empty object
- Split the string to an array and loop over it using forEach
- Increment the char value in the object by one. Or set the value to 1 if it does not exist
- Return the object keys and use reduce to find the highest value
const maxChar = (str) => {
const chars = {}
str.split('').forEach((char) => {
chars[char] = chars[char] + 1 || 1
})
return Object.keys(chars).reduce((a, b) => (chars[a] > chars[b] ? a : b))
}
Things to think about:
Handling capital letters
What should be returned if multiple numbers appear the same amount of times.
ย