sort-characters-by-freqency.dart (1252B)
1 //Given a string sort the characters by how many times they occur 2 //then return the new ordered string. To optimize my solution 3 //I would remove the entries from the map as they get used, but 4 //given how fast this code runs it would be an unneccessary hassle given 5 //that removing entries from a list when it is being iterated is not allowed thus 6 //forcing me to track it with a list. 7 //Time: 312ms Beats: 75% 8 //Memory: 144.5MB Beats: 100% 9 class Solution { 10 String frequencySort(String s) { 11 Map<String, int> vals = {}; 12 List<int> usages_list = []; 13 for(int i = 0 ; i < s.length ; ++i){ 14 vals[s[i]] = (vals[s[i]] ?? 0 ) + 1; 15 } 16 for(var entry in vals.entries){ 17 usages_list.add(entry.value); 18 } 19 usages_list.sort(); 20 usages_list = usages_list.reversed.toList(); 21 int current_itr = 0; 22 String ret_str = ""; 23 while(current_itr < usages_list.length){ 24 for(var entry in vals.entries){ 25 if(entry.value == usages_list[current_itr]){ 26 ret_str += entry.key * usages_list[current_itr]; 27 current_itr += 1; 28 if(current_itr >= usages_list.length){ 29 break; 30 } 31 } 32 } 33 } 34 35 return ret_str; 36 } 37 }