#451
Medium Algorithms Sort characters by frequency
Hash Table String Sorting Heap (Priority Queue) Bucket Sort Counting
75.1% acceptance
Jan 13, 2026
9174
333
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.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn frequency_sort(s: String) -> String {
let mut freq = HashMap::new();
for c in s.chars() {
*freq.entry(c).or_insert(0) += 1;
}
let mut chars: Vec<(char, i32)> = freq.into_iter().collect();
chars.sort_by(|a, b| b.1.cmp(&a.1));
let mut result = String::new();
for (c, count) in chars {
for _ in 0..count {
result.push(c);
}
}
result
}
}