Leetcode 451. Sort Characters By Frequency
Given a string s
, sort it in decreasing order based on the frequency of characters, and return the new string.
s
containing various characters.s
is at most 5 * 10^5
.s
consists of English letters and digits.n
is the length of the string.import java.util.*;
public class SortCharactersByFrequency {
public String frequencySort(String s) {
// Step 1: Calculate frequency of each character
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// Step 2: Create buckets for frequencies
List<Character>[] buckets = new List[s.length() + 1];
for (int i = 0; i <= s.length(); i++) {
buckets[i] = new ArrayList<>();
}
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
char c = entry.getKey();
int frequency = entry.getValue();
buckets[frequency].add(c);
}
// Step 3: Build the result string
StringBuilder result = new StringBuilder();
for (int i = buckets.length - 1; i >= 0; i--) {
for (char c : buckets[i]) {
for (int j = 0; j < i; j++) {
result.append(c);
}
}
}
return result.toString();
}
public static void main(String[] args) {
SortCharactersByFrequency solution = new SortCharactersByFrequency();
String s = "tree";
String sortedString = solution.frequencySort(s);
System.out.println(sortedString); // Output could be "eert" or "eetr"
}
}
frequencyMap
with character counts.i
contains a list of characters that appear i
times in the original string.In the provided code, edge cases like an empty string or a string with only one character are inherently handled, as the loops will simply not insert any characters or will just return the input character, respectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?