Taro Logo

Sort Characters By Frequency

#43 Most AskedMedium
Topics:
StringsArrays

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.

Example 1:

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

Constraints:

  • 1 <= s.length <= 5 * 105
  • s consists of uppercase and lowercase English letters and digits.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set does the input string consist of? Does it only contain ASCII characters, or should we account for full Unicode and surrogate pairs?
  2. How should characters with the exact same frequency be ordered relative to each other in the output string?
  3. What should be returned if the input string is empty or contains only a single character?
  4. Are case characters considered distinct? For example, should 'A' and 'a' be counted and sorted as separate characters or grouped together?
  5. Can I allocate additional memory to build a frequency map, or should the sorting and rearrangement be done under strict auxiliary space constraints?

Brute Force Solution

Approach

Imagine you have a jumbled box of colored blocks and want to reorganize them so that the blocks appearing most often are grouped together at the front. The brute force approach involves exhaustively checking every possible combination and grouping of those blocks until you find the arrangement where the most frequent blocks lead the way.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire collection of items to identify every unique type present.
  2. For each unique type, count how many times it appears by checking every single item in the collection from start to finish.
  3. Create a list of these types alongside their counts.
  4. Systematically test every possible way to order these types, placing different ones at the front to see what happens.
  5. For each ordering you test, write out the items according to that sequence and check if the most frequent types are indeed at the very beginning.
  6. Compare all the tested arrangements against each other to find the one where the counts decrease properly from highest to lowest.
  7. Finally, output that winning arrangement as your final result.

Code Implementation

import itertools


def frequency_sort(input_string):
    unique_characters = []
    for character in input_string:
        if character not in unique_characters:
            unique_characters.append(character)

    character_counts = []
    for unique_char in unique_characters:
        frequency_count = 0
        for scan_character in input_string:
            if scan_character == unique_char:
                frequency_count += 1
        character_counts.append((unique_char, frequency_count))

    # We generate all permutations to exhaustively test every possible ordering of unique items
    all_possible_permutations = list(itertools.permutations(character_counts))

    best_score_achieved = -1
    winning_arrangement = ()
    for candidate_permutation in all_possible_permutations:
        current_score = 0
        previous_frequency = float("inf")
        for item_char, item_freq in candidate_permutation:
            if item_freq <= previous_frequency:
                current_score += item_freq
                previous_frequency = item_freq
            else:
                current_score = -1
                break

        # We track the optimal permutation score to ensure elements descend strictly by frequency
        if current_score > best_score_achieved:
            best_score_achieved = current_score
            winning_arrangement = candidate_permutation

    reconstructed_result = []
    for target_char, target_freq in winning_arrangement:
        for repetition_index in range(target_freq):
            reconstructed_result.append(target_char)

    # We join characters together to form the final sorted string matching the brute force rules
    return "".join(reconstructed_result)

Big(O) Analysis

Time Complexity
O(n * u!) – To determine the time complexity of this brute force approach, we let n be the total length of the string and u be the number of unique characters. We first count frequencies by scanning the collection for each unique type, taking O(n * u) time. Next, step 4 and 5 require systematically generating and evaluating every possible permutation of the u unique character groups, which yields u! different orderings. For each of the u! permutations, we construct the resulting string by repeating characters according to their frequency, costing O(n) work per arrangement. Multiplying these steps together results in approximately u! * n operations, which dominates the complexity and simplifies to O(n * u!).
Space Complexity
O(N) – To execute the sorting and grouping process described in the steps, we utilize a hash map to store each unique character alongside its frequency count, plus a list of these pairs. In the worst-case scenario where all characters in the input string of length N are unique, the hash map and list will each store N elements. This requires extra memory that scales linearly with the input size N. Therefore, the total auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To rearrange the characters so that the most frequent ones appear first, we need to count how many times each character appears and then group them together by their popularity. Instead of guessing different combinations, we can tally everything up and then rebuild the text by placing the most common characters ahead of the rarer ones.

Here's how the algorithm would work step-by-step:

  1. Go through the entire message and keep a tally of how many times each individual character shows up.
  2. Organize your tally so that you know the exact count for every distinct character present.
  3. Arrange the characters in a descending lineup, placing the ones with the highest counts at the very front and the ones with the lowest counts at the back.
  4. Reconstruct a brand new message by taking the most popular character and writing it down as many times as it appeared in the original text.
  5. Move down your lineup to the next most popular character and write it down repeatedly according to its exact count.
  6. Continue this process until you have added every single character, ensuring all identical characters stay grouped together based on their frequency.

Code Implementation

from collections import Counter


def frequency_sort(input_message):
    # Counting frequencies first allows us to quantify the popularity of every character.
    character_counts = Counter(input_message)

    # Sorting by frequency places the most common characters at the front of our lineup.
    sorted_characters = sorted(character_counts.keys(), key=lambda char: character_counts[char], reverse=True)

    # Reconstructing the string ensures identical characters are grouped together.
    reconstructed_message_parts = [character * character_counts[character] for character in sorted_characters]

    return "".join(reconstructed_message_parts)

Big(O) Analysis

Time Complexity
O(n + k log k) – Counting the frequency of each character in the input string of length n takes O(n) time, where we iterate through every single character once. Next, sorting the unique characters based on their frequencies takes O(k log k) time, where k is the number of distinct characters in the string. Finally, reconstructing the output string by repeating each character according to its count takes O(n) operations. Combining these phases yields approximately n + k log k operations, which simplifies to O(n + k log k) or O(n log n) in the worst case.
Space Complexity
O(n) – To implement the frequency tally and sorted reconstruction, we use auxiliary data structures including a hash map to store character counts and a dynamic string builder to assemble the result. In the worst-case scenario where all characters are distinct, these structures store up to N characters. Therefore, the extra memory required scales linearly with the input size N, resulting in a space complexity of O(n).

Edge Cases

Empty string or string with a single character
How to Handle:
Return the input string directly as it is already sorted by frequency.
All characters have the exact same frequency
How to Handle:
Any arbitrary ordering among the characters is preserved stably or grouped correctly by the frequency bucket.
Characters with vastly different frequencies and large input size
How to Handle:
Using bucket sort or a max-heap ensures efficient scaling without relying purely on comparison-based sorting.
String with mixed case letters and digits
How to Handle:
Treat uppercase, lowercase, and numeric characters as distinct ASCII values in the frequency map.
Multiple valid solutions for characters with identical frequencies
How to Handle:
The problem accepts any valid arrangement, so any tie-breaking order among equal frequencies is acceptable.
Maximum length constraints causing memory and execution limits
How to Handle:
A linear time frequency counting algorithm avoids quadratic performance bottlenecks on large inputs.
0/52 completed