#451

Sort Characters By Frequency

Medium
Hash TableStringSortingHeap (Priority Queue)Bucket SortCountingHash MapHeap
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a frequency map and a max heap (priority queue) to efficiently sort characters by their frequency. This approach is faster and scales better with larger inputs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character using a HashMap.
  2. 2Step 2: Use a max heap to store characters based on their frequencies.
  3. 3Step 3: Construct the result string by repeatedly extracting characters from the heap.
solution.py13 lines
1# Full working Python code
2import heapq
3from collections import Counter
4
5def frequencySort(s):
6    freq = Counter(s)
7    max_heap = [(-count, char) for char, count in freq.items()]
8    heapq.heapify(max_heap)
9    result = []
10    while max_heap:
11        count, char = heapq.heappop(max_heap)
12        result.append(char * -count)
13    return ''.join(result)

Complexity note: The time complexity is O(n log n) due to the heap operations for sorting the characters. The space complexity is O(n) because we store the frequency of each character.

  • 1Using a frequency map is essential for counting occurrences efficiently.
  • 2Max heaps are useful for sorting elements based on custom criteria.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.