Sort Characters By Frequency - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "tree"
›
Output:
"eetr" or "eert"
💡 Note:
Character frequencies: e→2, t→1, r→1. Sort by frequency: e(2) comes first, then t(1) and r(1) in any order.
Example 2 — All Different Frequencies
$
Input:
s = "cccaaa"
›
Output:
"aaaccc" or "cccaaa"
💡 Note:
Both 'c' and 'a' appear 3 times, so they can be in any order, resulting in "aaaccc" or "cccaaa".
Example 3 — Single Character
$
Input:
s = "Aabb"
›
Output:
"bbAa" or "bbaA"
💡 Note:
Frequencies: b→2, A→1, a→1. Character 'b' appears most frequently, then 'A' and 'a' in any order.
Constraints
- 1 ≤ s.length ≤ 5 × 105
- s consists of uppercase and lowercase English letters and digits
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Parse input string and identify character frequencies
2
Frequency Sorting
Sort characters by their occurrence frequency
3
String Reconstruction
Build output with most frequent characters first
Key Takeaway
🎯 Key Insight: Count frequencies first, then sort by count to prioritize most frequent characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code