Sort characters by frequency
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's understanding of frequency counting, custom sorting with lexicographic tie-breaking, string manipulation, and time/space complexity analysis. It is commonly asked in the Coding & Algorithms domain to assess practical algorithmic implementation and efficiency trade-offs, and it primarily tests practical application rather than purely conceptual understanding.
Constraints
- 0 <= len(s) <= 10^5
- s consists of ASCII characters (codes 0-127)
- Tie-breaking is by ascending ASCII value, so 'A' (65) sorts before 'a' (97)
Examples
Input: ('tree',)
Expected Output: 'eert'
Explanation: 'e' appears twice (most frequent), then 'r' and 't' each appear once; 'r' < 't' so 'r' comes first.
Input: ('cccaaa',)
Expected Output: 'aaaccc'
Explanation: 'a' and 'c' both appear 3 times; tie broken by ascending order so 'a' (the smaller char) comes first.
Input: ('Aabb',)
Expected Output: 'bbAa'
Explanation: 'b' appears twice so it leads. 'A' and 'a' each appear once; 'A' (ASCII 65) sorts before 'a' (ASCII 97).
Input: ('',)
Expected Output: ''
Explanation: Empty input yields an empty string.
Input: ('a',)
Expected Output: 'a'
Explanation: Single character is returned unchanged.
Input: ('aAbBcC',)
Expected Output: 'ABCabc'
Explanation: Every character appears once, so all are ordered by ascending ASCII: uppercase A,B,C (65-67) before lowercase a,b,c (97-99).
Input: ('122333',)
Expected Output: '333221'
Explanation: '3' x3, then '2' x2, then '1' x1, strictly by descending frequency.
Hints
- Count the frequency of every character first using a hash map or a fixed-size array of length 128.
- Sort the distinct characters by a compound key: primary key is frequency descending, secondary key is the character itself ascending.
- Build the result by repeating each character by its count, in the sorted order.