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 * 105s consists of uppercase and lowercase English letters and digits.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:
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:
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)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:
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)| Case | How to Handle |
|---|---|
| Empty string or string with a single character | Return the input string directly as it is already sorted by frequency. |
| All characters have the exact same frequency | 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 | Using bucket sort or a max-heap ensures efficient scaling without relying purely on comparison-based sorting. |
| String with mixed case letters and digits | Treat uppercase, lowercase, and numeric characters as distinct ASCII values in the frequency map. |
| Multiple valid solutions for characters with identical frequencies | The problem accepts any valid arrangement, so any tie-breaking order among equal frequencies is acceptable. |
| Maximum length constraints causing memory and execution limits | A linear time frequency counting algorithm avoids quadratic performance bottlenecks on large inputs. |