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
Sort Characters By Frequency INPUT String s = "tree" t r e e Character Frequency Char Count t 1 r 1 e 2 ALGORITHM STEPS 1 Count Frequencies Build HashMap of char counts 2 Create Buckets Index = frequency (0 to n) 3 Fill Buckets Place chars in freq bucket 4 Build Result Iterate buckets high to low Bucket Array: idx 0 idx 1 idx 2 empty t, r e freq=0 freq=1 freq=2 FINAL RESULT Iterate from highest bucket: Bucket[2]: 'e' x 2 --> "ee" Bucket[1]: 't' x 1 --> "eet" Bucket[1]: 'r' x 1 --> "eetr" Output String: e e t r "eetr" or "eert" (both valid) OK - Sorted by frequency! Key Insight: Bucket Sort uses the frequency as the bucket index. Since max frequency = string length n, we create n+1 buckets. This achieves O(n) time complexity, faster than comparison-based O(n log n). TutorialsPoint - Sort Characters By Frequency | Bucket Sort Approach
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
89.0K Views
High Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen