MrainW's Home

All things come to those who wait!

0%

LeetCode 451. Sort Characters By Frequency

Question

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.

https://leetcode.com/problems/sort-characters-by-frequency/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);
List<Character> [] bucket = new List[s.length() + 1];
for (char key : map.keySet()){
int frequency = map.get(key);
if (bucket[frequency] == null) bucket[frequency] = new ArrayList<>();
bucket[frequency].add(key);
}
StringBuilder sb = new StringBuilder();
for (int pos = bucket.length - 1; pos > 0; pos--)
if (bucket[pos] != null)
for (char c : bucket[pos])
for (int i = 0; i < pos; i++)
sb.append(c);
return sb.toString();
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels