[Solved] Sort the String According to the Frequency of Character in Java

[Solved] Sort the String According to the Frequency of Character in Java

Problem Statement / TASK: You are given a string and your task is to sort the string according to the frequency of character and return the final string.

EXAMPLE 1 :

Input : "tree" 
Output : "eetr"

Explanation: The frequency of each character in the word is [1, 1, 2, 2] after sorting according to the frequency the output will be “eetr”.

EXAMPLE 2 :

Input : "hello"
Output : "lleho"

Solution

Approach and Algorithm

  1. First, we will make the character array of the characters of the string.
  2. Then count the frequency of each character in the string.
  3. Taking the frequency as the main array sort the character array.
  4. Then make the string of that char array.

Java Program

Prerequisite:

Java Code:

import java.util.Arrays;

public class SortStringByFrequency {
    public static void main(String[] args) {
        String s = "tree";
        int f[] = new int[s.length()];
        char[] st = s.toCharArray();
        for (int i = 0; i < st.length; i++) {
            f[i] = countFrequency(st, st[i]);
        }
//        System.out.println(Arrays.toString(f));
        System.out.println(sortArray(st, f));
    }

    public static int countFrequency(char[] a, char b) {
        int count = 0;
        for (char i : a){
            if (i == b)
                count++;
        }
        return count;
    }

    public static String sortArray(char[] a, int[] b) {
        int t = 0;char c;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0;j < a.length - i - 1;j++) {
                if (b[j] < b[j + 1]) {
                    t = b[j];
                    b[j] = b[j + 1];
                    b[j + 1] = t;

                    c = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = c;
                }
            }
        }
        System.out.println(Arrays.toString(b));
        return Arrays.toString(a);
    }
}

This is all about a code to sort the string according to the frequency of character. You can solve the above coding challenge in C/C++, Python or any of the programming languages of your choice.

Leave a Reply

Your email address will not be published. Required fields are marked *