...

/

Frequency Sort (medium)

Frequency Sort (medium)

Problem Statement

Given a string, sort it based on the decreasing frequency of its characters.

Example 1:

Input: "Programming"
Output: "rrggmmPiano"
Explanation: 'r', 'g', and 'm' appeared twice, so they need to appear before any other character.

Example 2:

Input: "abcbab"
Output: "bbbaac"
Explanation: 'b' appeared three times, 'a' appeared twice, and 'c' appeared only once.

Try it yourself

Try solving this question here:

import java.util.*;
class FrequencySort {
public static String sortCharacterByFrequency(String str) {
// TODO: Write your code here
return "";
}
public static void main(String[] args) {
String result = FrequencySort.sortCharacterByFrequency("Programming");
System.out.println("Here is the given string after sorting characters by frequency: " + result);
result = FrequencySort.sortCharacterByFrequency("abcbab");
System.out.println("Here is the given string after sorting characters by frequency: " + result);
}
}

Solution

This problem follows the Top ‘K’ Elements pattern, and shares similarities with Top ‘K’ Frequent Numbers.

We can follow the same approach ...