Max Chars Problem

Max Chars Problem

Return the character that is most commonly used in the given string

ยท

2 min read

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

  1. Create an empty object variable
  2. Loop Through each character in the string
  3. Check if the character is in the object variable
  4. 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

  1. Set 2 new variables. A empty string (maxChar) and a integer starting at 0 (max)
  2. Loop through the object variable
  3. Check if the current chars value is higher then the integer value (max)
  4. 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
  5. 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

  1. Create an empty object
  2. Split the string to an array and loop over it using forEach
  3. Increment the char value in the object by one. Or set the value to 1 if it does not exist
  4. 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.

ย