DEV Community

Cover image for JS Coding Question #9: Get Max Character In A String [Challenging]
Let's Code
Let's Code

Posted on

4 2

JS Coding Question #9: Get Max Character In A String [Challenging]

Interview Question #9:

Write a function that will return the max character in a string.๐Ÿค” You may get variation to the question as well like Write a function that will return that most commonly used character in a sentence or similar.

Additional Rules:

  1. Treat lowercase and uppercase the same
  2. Only count alphabetic characters, no symbols and numbers
  3. Return one max character in case of multiple max characters

If you need practice, try to solve this on your own without looking at the solution below.

Feel free to bookmark ๐Ÿ”– even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Codepen:

If you want to play around and experiment with the code: https://codepen.io/angelo_jin/pen/abwYGPo

Solution below will cycle on every string and create a map. Once the map is created, cycle on the map and use the variables created to see if the current char has greater count. Assign char and max count accordingly.

// Helper function to remove non alphabetic characters and transform string to lowercase
function normalizeString(str) {
  return str
    .replace(/[^\w]/g, '')
    .toLowerCase()
}

function getMaxChar(str) {
  const charMap = {}
  let max = 0
  let maxChar = ''

  for (let char of normalizeString(str)) {
    if (charMap[char]) {
      charMap[char]++
    } else {
      charMap[char] = 1
    }
  }

  for (let char in charMap) {
    if (charMap[char] > max) {
      max = charMap[char]
      maxChar = char
    }
  }

  return maxChar
}
Enter fullscreen mode Exit fullscreen mode

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

Video below if you prefer instead of bunch of text/code ๐Ÿ‘๐Ÿ˜Š

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly โ€” using the tools and languages you already love!

Learn More

Latest comments (9)

Collapse
 
corebugcreator profile image
corebugcreator โ€ข

Image description

Collapse
 
frontendengineer profile image
Let's Code โ€ข

would work too. thanks

my only concern is the .sort as it will be slow when dataset is huge but it is not a problem on small dataset. Could prolly use lib or even custom merge sort or something equivalent

Collapse
 
grahamthedev profile image
GrahamTheDev โ€ข โ€ข Edited

The only issue with your example is the double loop, you can achieve the same with the following which takes advantage of how split works:

99% sure it returns the same as your function.

Collapse
 
frontendengineer profile image
Let's Code โ€ข โ€ข Edited

thank you for this solution! Learned something today. I took your example and translate it to more readable form.

function getMaxChar(str){
  let max = 0
  let maxChar = ''
  const normalizedString = str.toLowerCase().replace(/[^a-z']/g, "")

  normalizedString.split('')
    .forEach(char => {
      if (normalizedString.split(char).length > max) {
          max = normalizedString.split(char).length;
          maxChar = char;
       }
    })

  return maxChar;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grahamthedev profile image
GrahamTheDev โ€ข

Yeah sorry, I already had the main part of the function as part of a code snippets library and it is partially minimised due to a mistake I made...I have about 100 snippets that aren't very readable like that!

I have copied the normalisedString.split() etc. part back into my code snippets library so it is readable again, so thanks for that ๐Ÿ˜€

Maybe I will finally get around to fixing them all as they do come in handy and it just laziness stopping me fixing them!

Thread Thread
 
frontendengineer profile image
Let's Code โ€ข

LOL dude, nothing to apologize from. You actually improved my solution helping out myself and other folks who will read this post. So thank you and I am glad that you came in and share that snippet. ๐Ÿ‘

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข
Comment hidden by post author
Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข โ€ข Edited

Will you engage in a civil conversation? Or continue to hide comments?

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started โ†’

๐Ÿ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere โ€œthank youโ€ often brightens someoneโ€™s dayโ€”share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay