We count frequencies and then use a Max-Heap to extract characters in decreasing order of frequency.
- Count frequencies.
- Use a Max-Heap (Python's
heapqwith negative frequencies) to store(-freq, char). - While the heap is not empty:
- Pop the character with the highest frequency.
- Append it
freqtimes to the result string.
- Return the string.
- Time Complexity: O(N log U), where U is the number of unique characters.
- Space Complexity: O(N).
import heapq
from collections import Counter
def frequency_sort(s):
counts = Counter(s)
# Use max-heap (negative values for heapq)
max_heap = [(-freq, char) for char, freq in counts.items()]
heapq.heapify(max_heap)
res = []
while max_heap:
freq, char = heapq.heappop(max_heap)
res.append(char * (-freq))
return "".join(res)