Sort Characters by Frequency

Hashing, Sorting, and Parsing DSA practice problem on Onlearn.

Difficulty: easy.

Topics: Sort Characters by frequency, Frequency Counting, Strings, Map, Hash Tables, Sorting, Arrays, Time Complexity, Space Complexity, Big O Notation, frequency counting, sorting algorithms, priority queue, string manipulation, Heap (Priority Queue).

Problem Statement 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. If multiple characters have the same frequency, their relative order can be arbitrary. Input A single string s consisting of lowercase English letters, uppercase English letters, and digits. Output Return the sorted string. Constraints 1 <= s.length <= 5 10^5 Examples Example 1: Input: s = "tree" Output: "eert" Explanation: 'e' appears twice, 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. 'r' and 't' can be in any order. "eetr" is also a valid answer. Example 2: Input: s = "cccaaa" Output: "aaaccc" Explanation: 'c' and 'a' both appear three times. "cccaaa" is also a valid answer. Note that "aaaCCC" is an invalid answer, as the case sensitivity matters. Example 3: Input: s = "Aabb" Output: "bbAa" Explanation: 'A' and 'a' are treated as different characters. 'b' appears twice, 'A' and 'a' both appear once. So 'b' must appear before 'A' and 'a'. "Aabb" is also a valid answer.