AlgoMaster Logo

Sort Characters By Frequency

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute-force sorting

Intuition:

The simplest way to solve the problem is to count the frequency of each character and then sort the characters based on their frequency. This can be achieved using a hashmap to count frequencies and then converting it to a list or array for sorting.

Steps:

  1. Create a hashmap to store the frequency of each character.
  2. Convert the hashmap to a list of characters.
  3. Sort the list using a custom comparator based on frequency.
  4. Build the resulting string based on sorted order.

Code:

2. Bucket Sort

Intuition:

To improve on the sorting time, we can use bucket sort which exploits the fact that frequency maximum is bounded by the string length. By placing characters into buckets indexed by frequency, we can directly build the string.

Steps:

  1. Count frequency of each character and find the maximum frequency.
  2. Create buckets where each index corresponds to characters that have that frequency.
  3. Fill the buckets with the corresponding characters.
  4. Traverse the buckets in reverse order to create the output string by frequency.

Code:

3. Using Priority Queue (Optimal)

Intuition:

We can also use a max-heap to always extract the most frequent element. This provides an efficient way to manage and prioritize elements by frequency without fully sorting the list of characters.

Steps:

  1. Count frequency of each character.
  2. Use a priority queue (max-heap) to store entries sorted by frequency.
  3. Extract characters from the priority queue and append to the result string.

Code: