Problem
Reorder a string so that characters appear in decreasing order of frequency. If two characters have the same frequency, either order is acceptable.
Original: LeetCode 451: Sort Characters By Frequency.
Examples
Example 1
`s = "tree"``"eert"`"eetr" is also valid: both r and t appear once.
Example 2
`s = "cccaaa"``"aaaccc"`"cccaaa" is also valid, but "cacaca" is not, because equal characters must be together.
Example 3
`s = "Aabb"``"bbAa"`"bbaA" is also valid. "A" and "a" are different characters.
Constraints
1 <= s.length <= 5 * 10^5sconsists of uppercase and lowercase English letters and digits.
Hints
Hint 1
Case matters: 'A' and 'a' are different characters. The whole run of a character is written together in the usual construction, but any arrangement with the right frequencies is accepted if you sort only by count.
Hint 2
"Order by how often it appears" is frequency counting followed by a sort or a bucket list.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Count, then sort the entire string with a custom comparator on the counts. That is O(n log n) on the full length.
Optimal. Count in a map, then sort only the distinct characters by count and rebuild the string. The sort is on the alphabet size, which is much smaller than n in the usual case.
Alternative. Bucket sort: put characters into an array of lists indexed by frequency, then walk the buckets from n down to 1. That is linear in n plus the alphabet.
Complexity
- Time
- O(n + m log m)
O(n + m log m) time, where m is the number of distinct characters, and O(n) space to rebuild the string.
- Space
- O(n)
Code
from collections import Counter
def frequency_sort(s: str) -> str:
count = Counter(s)
chars = sorted(count, key=lambda c: -count[c])
return "".join(c * count[c] for c in chars)
if __name__ == "__main__":
t = frequency_sort("tree")
assert t in {"eert", "eetr"}
c = frequency_sort("cccaaa")
assert c in {"aaaccc", "cccaaa"}
x = frequency_sort("Aabb")
assert Counter(x) == Counter("Aabb") and x[:2] == "bb"
print("ok")import java.util.ArrayList;
import java.util.HashMap;
public class SortCharactersByFrequency {
static String frequencySort(String s) {
var count = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
count.merge(s.charAt(i), 1, Integer::sum);
}
var chars = new ArrayList<>(count.keySet());
chars.sort((a, b) -> Integer.compare(count.get(b), count.get(a)));
var out = new StringBuilder();
for (var c : chars) {
out.append(String.valueOf(c).repeat(count.get(c)));
}
return out.toString();
}
static boolean sameFreq(String a, String b) {
if (a.length() != b.length()) return false;
var ca = new HashMap<Character, Integer>();
var cb = new HashMap<Character, Integer>();
for (int i = 0; i < a.length(); i++) ca.merge(a.charAt(i), 1, Integer::sum);
for (int i = 0; i < b.length(); i++) cb.merge(b.charAt(i), 1, Integer::sum);
return ca.equals(cb);
}
public static void main(String[] args) {
String t = frequencySort("tree");
if (!t.equals("eert") && !t.equals("eetr")) throw new AssertionError(t);
if (!sameFreq(t, "tree")) throw new AssertionError();
String c = frequencySort("cccaaa");
if (!c.equals("aaaccc") && !c.equals("cccaaa")) throw new AssertionError(c);
String x = frequencySort("Aabb");
if (!sameFreq(x, "Aabb")) throw new AssertionError(x);
if (x.charAt(0) != 'b' || x.charAt(1) != 'b') throw new AssertionError(x);
System.out.println("ok");
}
}Edge cases
- Official samples include "tree", which may be "eert" or "eetr"; "cccaaa", which may be "aaaccc" or "cccaaa"; and "Aabb", where the two 'b' characters must come first.
- Uppercase and lowercase are counted separately.
Follow-ups
- Top K Frequent Words adds a lexical tie-break and only keeps k items, so a heap or a sort with a second key is needed.
Interview script
"I count frequencies, sort the distinct characters by count descending, and write each character out that many times. Sorting the alphabet is enough; I do not need to sort every character in the string."
Source: LeetCode 451: Sort Characters By Frequency Source: Java SE 17 API: Map.merge)
Single-pass array scans
Sources (2)
- LeetCode 451: Sort Characters By Frequencyleetcode.com
- Java SE 17 API: Map.mergedocs.oracle.com