Created
September 11, 2017 16:39
-
-
Save interdigitize/5720b84f7c19ffae2507cbcaa7c35be8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Given a string, sort it in decreasing order based on the frequency of characters. | |
| var frequencySort = function(s) { | |
| var charFreq = {}; | |
| for (var i = 0; i < s.length; i++) { | |
| if(charFreq[s[i]]) { | |
| charFreq[s[i]] = charFreq[s[i]] + 1; | |
| } else { | |
| charFreq[s[i]] = 1; | |
| } | |
| } | |
| var freq = 0; | |
| var str = ''; | |
| for (char in charFreq) { | |
| if(freq > charFreq[char]) { | |
| var freq = charFreq[char]; | |
| for(var i = 0; i < freq; i++) { | |
| str += char; | |
| } | |
| } else { | |
| var freq = charFreq[char]; | |
| for(var i = 0; i < freq; i++) { | |
| str = char + str; | |
| } | |
| } | |
| } | |
| return str; | |
| }; | |
| var assert = function(actual, expected, alt) { | |
| if (actual === expected || actual === alt) { | |
| return console.log('PASSED!!'); | |
| } | |
| console.log(`Expected ${expected} but got ${actual}.`); | |
| } | |
| //-------------------EXAMPLES------------------------- | |
| assert(frequencySort('tree'), 'eert'); | |
| // Input: | |
| // "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. | |
| assert(frequencySort('cccaaa'), 'cccaaa', 'aaaccc'); | |
| // Input: | |
| // "cccaaa" | |
| // | |
| // Output: | |
| // "cccaaa" | |
| // | |
| // Explanation: | |
| // Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. | |
| // Note that "cacaca" is incorrect, as the same characters must be together. | |
| assert(frequencySort('Aabb'), 'bbAa', 'bbaA'); | |
| // Input: | |
| // "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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment