DEV Community

Ezekiel nwuguru
Ezekiel nwuguru

Posted on

DAY 5: Sort characters by frequency

Hey! It's day 5 of 10 days coding challenge with I4G. Today's challenge was to write a code that sorts characters by frequency.

Thought Process:
Understanding of problem: The problem here is to write a code that checks through a string and sorts each character based on their frequency of occurrence
Solution: In order to achieve this, I utilized some java classes such as HashMap and StringBuilder. The HashMap is java classes uses the Map interface to store key pair values. In this task I used it to iterate through the given string and store each character and its count in a Map. The character map was then sorted based on frequency and then the string builder was used to build the result back to a string.

Algorithm:

  1. Instantiate the string builder to builder
  2. Instantiate the HashMap using the Map interface to charMap as a key pair of Character and Integer
  3. User for loop to traverse through the string and store it in the charMap
  4. Sort the character map for each key-value pairs
  5. Using another for loop iterate through the key-value pair and append to the string builder.
  6. Return the builder in string format

Checkout the code here: https://leetcode.com/submissions/detail/808336602/

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.