Data Structures and Algorithms(Day-5 #I4G10DaysOfCodeChallenge)
Sort Characters By Frequency Challenge
Table of contents
Introduction
Phew!!!!! It's the fifth day of the challenge already and it's challenge cannot come any better than this. Today's challenge was the Sort Characters By Frequency Challenge.
Challenge
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
Example 1:
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
Click Here to view the challenge on Leetcode
Explanation
What is required from today's challenge is to read through a given string and return an output string starting from the character that appears the most (outputting all its repetitons) to least appearing character(s). The examples above gives the required description.
Solution
I solved this problem with an object.
First, initialize an empty object.
Loop through the given string and for any of its character, represent it in the object as a property and increment it by one, e.g
for(...){
object[a character from the string]=object[a character from the string]+1 || 1
}
Once the looping is done, we now get an object having the individual string characters as properties and their frequencies as key-value pairs.
Push the object properties (key-value pairs) into an array ,so that the frequencies of the string characters can be sorted. A 2D array is the result of this step.
array=[[character 1,frequency 1],[character 2,frequency 2],...]
Next, devise a means to sort the frequencies in the array (string characters) in descending order.
After the sorting is done, a 2D-array starting from characters with high frequencies to that of lower frequencies is formed.
Prior to this stage, a result variable has to be declared to hold and output the result. Then, from the sorted array, loop through it and for each character, repeat it the number of times it frequency says and append it to the result variable.
Once step 9 is done, return the result variable which is now the characters of the string sorted from high to low frequency having the required repetitons.
Thanks for reading.