Coding challenge Day-5

Coding challenge Day-5

Fifth day of I4G coding challenge

Sort Characters by Frequency

Question

Today's challenge was challenging even though I was able to use JavaScript. It was a test about sorting string with the highest occurrence letter coming first and moving down in descending order. For example

input = "tree"
output = "eert"

It was tricky just looking at it. Let's go through my thought process and see how I approached it

Thought Process

Seeing the question, the following came to my mind:

  1. Separate the string and have individual characters stored up in an array.

  2. Loop through the array counting and storing the reoccurrence of each character in an object form. Something like

frequency: { character: count}
  1. After getting the frequency, create a new array that will nest an array of individual characters and the frequency.

  2. Sort the by their frequency count from highest to lowest then extract the character in that other with a map() method into a new sorted array.

  3. Join the characters together using join() method.

Implementation

I was able to implement the code exactly the way I described in my thought process using methods like

  • split()

  • sort()

  • map()

  • forEach()

What I learnt

Learnt more about the descending order type of sorting. It was fun working on this challenge because it was a little more complex

Conclusion

Answer

My code consumed a lot of memory space(75MB), looking to optimize it but for now, it pass the test and that's a big plus.

Thank you for reading through!

Day five(5) done, five(5) more days to go!

You can follow me on Twitter