Problem 298717 · medium · Phase 02 Linear Data Structures

Order Letters by Popularity

strings · counting · sorting

Write frequency_sort(s) that rearranges the characters of s so that characters with higher frequency come first, with all copies of a character grouped together. Characters with equal frequency are ordered by their ASCII value (so uppercase letters come before lowercase ones, and digits before letters). Every character counts, and comparison is case-sensitive.

Examples

Input:  s = "tree"
Output: "eert"

Input:  s = "cccaaa"
Output: "aaaccc"
Explanation: equal counts, and "a" < "c".

Input:  s = "Aabb"
Output: "bbAa"

Constraints

  • 0 <= len(s) <= 10**5, printable ASCII
  • Target: O(n + d log d) where d is the number of distinct characters

Goals

  • Count character frequencies
  • Sort by count descending with a deterministic tie-break
  • Rebuild a string from counts
Starting Python…