public String frequencySort(String s) { if (s == null) { returnnull; } Map<Character, Integer> map = newHashMap<>(); for (inti=0; i < s.length(); ++i) { Characterc= s.charAt(i); map.put(c, map.getOrDefault(c, 0) + 1); } List<Character> arrayList = newArrayList<>(map.keySet()); Collections.sort(arrayList, (n1, n2) -> (map.get(n2) - map.get(n1))); // build the string StringBuildersb=newStringBuilder(); for (Character c : arrayList) { intcount= map.get(c); while (count > 0) { sb.append(c); count -= 1; } } return sb.toString(); }
Time: $O(N\log{M})$ where $M$ is the number of distinct characters. Space: $O(N)$
$O(M)$ the array and the map (with greater overhead).
$O(N)$ the output string.
Using TreeSet here is not a good idea!
The code will not give correct results. In the tree example, r will be missing. It is because equals and compareTo methods should be consistent. Since we have a comparator (n1, n2) - > (map.get(n2)- map.get(n1)), when t and r have the same count, they are treated as the “same” characters in the set. Thus, t won’t be added into the set.