Related Articles
Sort an array of Strings according frequency
• Last Updated : 10 Jun, 2020

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

Examples:

Input: arr[] = {“Geeks”, “for”, “Geeks”}
Output: {“for”, “Geeks”}
Explanation:
As string “Geeks” have 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 same frequency, the array is sorted in the lexicographical order.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach The idea is to use custom comparator to sort the array of strings with its 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 help of custom comparator such that if two strings have different frequency, the string with lower frequency is stored before. Otherwise if the frequency is 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 ` `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 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 > 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; ` `} `

## 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``]

Output:

```arc, for, Geeks,
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :