Open In App

Sort an array of Strings according frequency

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of strings arr[], the task is to sort the array of strings according to the frequency of each string, in ascending order. If two elements have the same frequency, then they are sorted into lexicographical order.

Examples: 

Input: arr[] = {“Geeks”, “for”, “Geeks”} 
Output: {“for”, “Geeks”} 
Explanation: 
As the string “Geeks” has a frequency of 2 in the given array, 
Hence, the position of the string “Geeks” will be 2

Input: arr[] = {“abc”, “pqr”, “pqr”, “abc”} 
Output: {“abc”, “pqr”} 
Explanation: 
As both the strings have the same frequency, the array is sorted in the lexicographical order.  

Approach The idea is to use a custom comparator to sort the array of strings with their frequency, as per the following steps.
 

  • A map data structure is used to store the strings based on their frequency as (frequency, string) pairs.
  • Sort these pairs with the help of a custom comparator such that if two strings have different frequencies, the string with a lower frequency is stored before. Otherwise, if the frequency is the same, then compare the strings lexicographically
     

Below is the implementation of the above approach: 

C++




// C++ implementation to sort the
// array of strings by its frequency
 
#include <bits/stdc++.h>
using namespace std;
 
// Custom comparator function to
// sort the string by its frequency
bool cmp(pair<int, string> x,
         pair<int, string> y)
{
 
    // Condition to check if the
    // frequency of the string is less
    if (x.first < y.first) {
        return true;
    }
 
    // Condition to check if the
    // frequency of the string is greater
    else if (x.first > y.first) {
        return false;
    }
 
    // Condition when frequency of
    // the strings is equal
    else {
 
        // Condition to check if the
        // first string is lexicographically
        // smaller than second string
        if (x.second < y.second) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
// Function to sort the array of strings
// by its frequency in the array
void printArraystring(string str[], int n)
{
    unordered_map<string, int> m;
 
    // Loop to store the frequency
    // of a string in a hash-map
    for (int i = 0; i < n; i++) {
        m[str[i]]++;
    }
 
    // Iterator for the map
    vector<pair<int, string> > vec;
 
    // Loop to store the frequency and
    // string in a vector
    for (auto it = m.begin(); it != m.end();
         it++) {
        vec.push_back(
            make_pair(it->second, it->first));
    }
 
    // Sort the string
    // using custom comparator
    sort(vec.begin(), vec.end(), cmp);
 
    // Loop to print the sorted vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i].second << ", ";
    }
}
 
// Driver Code
int main()
{
    string arr[] = { "Geeks", "for", "Geeks",
                     "for", "arc" };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function to perform sorting
    printArraystring(arr, n);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
 
public class Main {
 
    static class Pair<K, V> {
        K key;
        V val;
 
        Pair(K k, V v)
        {
            key = k;
            val = v;
        }
    }
 
    // Function to sort the array of strings
    // by its frequency in the array
    static void printArraystring(String str[], int n)
    {
        HashMap<String, Integer> m = new HashMap<>();
 
        // Loop to store the frequency
        // of a string in a hash-map
        for (int i = 0; i < n; i++) {
            m.put(str[i], m.getOrDefault(str[i], 0) + 1);
        }
 
        // Iterator for the map
        List<Pair<Integer, String> > vec
            = new ArrayList<>();
 
        // Loop to store the frequency and
        // string in a vector
        for (String st : m.keySet()) {
            vec.add(new Pair(m.get(st), st));
        }
 
        // Sort the string
        // using custom comparator
        Collections.sort(vec, (x, y) -> {
           
            // Condition to check if the
            // frequency of the string is less
            if (x.key < y.key) {
                return -1;
            }
 
            // Condition to check if the
            // frequency of the string is greater
            else if (x.key > y.key) {
                return 1;
            }
 
            // Condition when frequency of
            // the strings is equal
            else {
 
                // Condition to check if the
                // first string is lexicographically
                // smaller than second string
                if (x.val.compareTo(y.val) < 0) {
                    return -1;
                }
                else {
                    return 1;
                }
            }
        });
 
        // Loop to print the sorted vector
        for (int i = 0; i < vec.size(); i++) {
            System.out.print(vec.get(i).val + ", ");
        }
    }
 
    public static void main(String[] args)
    {
        String arr[]
            = { "Geeks", "for", "Geeks", "for", "arc" };
        int n = arr.length;
       
        // Function to perform sorting
        printArraystring(arr, n);
    }
}
 
// This code is contributed by aadityaburujwale.


Python 3




# Python 3 implementation to sort the
# array of strings by its frequency
 
# Custom comparator function to
# sort the string by its frequency
def srt(x):
    for i in range(len(x)-1):
        for j in range(i+1,len(x)):
            if(x[i][0]>x[j][0]):
                temp = x[j]
                x[j] = x[i]
                x[i] = temp
            elif(x[i][0] == x[j][0]):
                if(x[i][1]<x[j][1]):
                    temp = x[j]
                    x[j] = x[i]
                    x[i] = temp
                     
 
# Function to sort the array of strings
# by its frequency in the array
def printArraystring(str,n):
    m = {str[i]:0 for i in range(n)}
 
    # Loop to store the frequency
    # of a string in a hash-map
    for i in range(n):
        m[str[i]] += 1
 
    # Iterator for the map
    vec = []
 
    # Loop to store the frequency and
    # string in a vector
    for key,value in m.items():
        vec.append([value,key])
 
    # Sort the string
    # using custom comparator
    srt(vec)
 
    # Loop to print the sorted vector
    for i in range(len(vec)):
        if i==len(vec)-1:
            print(vec[i][1])
        else:
            print(vec[i][1],end = ",")
         
 
# Driver Code
if __name__ == '__main__':
    arr = ["Geeks", "for", "Geeks","for", "arc"]
    n = len(arr)
 
    # Function to perform sorting
    printArraystring(arr, n)
 
# This code is contributed by Surendra_Gangwar


C#




using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Custom comparator function to
  // sort the string by its frequency
  public static int cmp(KeyValuePair<int, string> x,
                        KeyValuePair<int, string> y)
  {
 
    // Condition to check if the
    // frequency of the string is less
    if (x.Key < y.Key) {
      return 1;
    }
 
    // Condition to check if the
    // frequency of the string is greater
    else if (x.Key > y.Key) {
      return 1;
    }
 
    // Condition when frequency of
    // the strings is equal
    else {
 
      // Condition to check if the
      // first string is lexicographically
      // smaller than second string
      if (x.Value.Length < y.Value.Length) {
        return 1;
      }
    }
    return -1;
  }
 
  // Function to sort the array of strings
  // by its frequency in the array
  public static void printArraystring(string[] str, int n)
  {
    var m = new Dictionary<string, int>();
 
    // Loop to store the frequency
    // of a string in a hash-map
    for (int i = 0; i < n; i++) {
      if (m.ContainsKey(str[i]))
        m[str[i]] = m[str[i]] + 1;
      else
        m[str[i]] = 1;
    }
 
    // Iterator for the map
    var vec = new List<KeyValuePair<int, string> >();
 
    // Loop to store the frequency and
    // string in a vector
    foreach(KeyValuePair<string, int> entry in m)
    {
      vec.Add(new KeyValuePair<int, string>(
        entry.Value, entry.Key));
    }
 
    // Sort the string
    // using custom comparator
    vec.Sort(cmp);
 
    // Loop to print the sorted vector
    for (int i = 0; i < vec.Count; i++) {
      Console.Write(vec[i].Value + ", ");
    }
  }
 
  static public void Main()
  {
 
    string[] arr
      = { "Geeks", "for", "Geeks", "for", "arc" };
    int n = arr.Length;
 
    // Function to perform sorting
    printArraystring(arr, n);
  }
}
 
// This code is contributed by akashish__


Javascript




<script>
// Javascript program
 
// Custom comparator function to
// sort the string by its frequency
function cmp(x, y)
{
   
    // Condition to check if the
    // frequency of the string is less
    if (x[0] < y[0]) {
        return -1;
    }
   
    // Condition to check if the
    // frequency of the string is greater
    else if (x[0] > y[0]) {
        return 1;
    }
   
    // Condition when frequency of
    // the strings is equal
    else if (x[0] === y[0]){
   
        // Condition to check if the
        // first string is lexicographically
        // smaller than second string
        if (x[1] < y[1]) {
            return 1;
        }
        else {
            return -1;
        }
    }
}
   
// Function to sort the array of strings
// by its frequency in the array
function printArraystring(str, n)
{
    var m = {};
    for (i = 0; i < n; i++) {
        m[str[i]] = 0;
    }
     
    // Loop to store the frequency
    // of a string in a hash-map
    for (i = 0; i < n; i++) {
        m[str[i]]++;
    }
   
    // Iterator for the map
    var vec = new Array(n);
    for (i = 0; i < n; i++) {
        vec[i] = [];
    }
   
    // Loop to store the frequency and
    // string in a vector
    var k = 0
    for (var it in m) {
        vec[k] = [m[it], it];
        k += 1;
    }
   
    // Sort the string
    // using custom comparator
    vec.sort(cmp);
   
    // Loop to print the sorted vector
    for (var i = 0; i < k; i++) {
        document.write(vec[i][1]+", ");
    }
}
 
var arr = [ "Geeks", "for", "Geeks", "for", "arc" ];
n = arr.length;
 
// Function to perform sorting
printArraystring(arr, n);
</script>


Output

arc, Geeks, for, 

Time Complexity: O(nlogn)

Space Complexity: O(n)



Last Updated : 20 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads