Sort an array of strings based on count of distinct characters
Last Updated :
21 Dec, 2022
Given a string array arr[] as input, the task is to print the words sorted by number of distinct characters that occur in the word, followed by length of word.
Note:
- If two words have same number of distinct characters, the word with more total characters comes first.
- If two words have same number of distinct characters and same length, the word that occurs earlier in the sentence must be printed first.
Examples:
Input: arr[] = {"Bananas", "do", "not", "grow", "in", "Mississippi"}
Output: do in not Mississippi Bananas grow
Explanation:
After sorting by the number of unique characters and the length the output will be, do in not Mississippi Bananas grow.
Input: arr[] = {"thank", "you", "geeks", "world"}
Output: you geeks thank world
Explanation:
After sorting by the number of unique characters and the length the output will be, you geeks thank world.
Approach: The idea is to use Sorting.
- Initialize a map data structure to count all the possible distinct characters from each string of the given array.
- Then sort the array by passing the comparator function, where sorting is done by the number of unique character in word and length of word.
- After sorting is done, print the strings of the array.
For example s = "Bananas do not grow in Mississippi"
Word Number of unique character Length of Word
do 2 2
in 2 2
not 3 3
Bananas 4 7
grow 4 4
Mississippi 4 11
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return no of
// unique character in a word
int countDistinct(string s)
{
// Initialize map
unordered_map<char, int> m;
for (int i = 0; i < s.length(); i++) {
// Count distinct characters
m[s[i]]++;
}
return m.size();
}
// Function to perform sorting
bool compare(string& s1, string& s2)
{
if (countDistinct(s1) == countDistinct(s2)) {
// Check if size of string 1
// is same as string 2 then
// return false because s1 should
// not be placed before s2
if (s1.size() == s2.size()) {
return false;
}
return s1.size() > s2.size();
}
return countDistinct(s1) < countDistinct(s2);
}
// Function to print the sorted array of string
void printArraystring(string str[], int n)
{
for (int i = 0; i < n; i++)
cout << str[i] << " ";
}
// Driver Code
int main()
{
string arr[] = { "Bananas", "do",
"not", "grow", "in",
"Mississippi" };
int n = sizeof(arr)
/ sizeof(arr[0]);
// Function call
sort(arr, arr + n, compare);
// Print result
printArraystring(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to return no of
// unique character in a word
static int countDistinct(String s)
{
// Initialize map
Map<Character, Integer> m = new HashMap<>();
for(int i = 0; i < s.length(); i++)
{
// Count distinct characters
if (m.containsKey(s.charAt(i)))
{
m.put(s.charAt(i),
m.get(s.charAt(i)) + 1);
}
else
{
m.put(s.charAt(i), 1);
}
}
return m.size();
}
// Function to print the sorted
// array of string
static void printArraystring(String[] str,
int n)
{
for(int i = 0; i < n; i++)
{
System.out.print(str[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
String[] arr = { "Bananas", "do",
"not", "grow",
"in", "Mississippi" };
int n = arr.length;
// Function call
Arrays.sort(arr, new Comparator<String>()
{
public int compare(String a, String b)
{
if (countDistinct(a) ==
countDistinct(b))
{
// Check if size of string 1
// is same as string 2 then
// return false because s1 should
// not be placed before s2
return (b.length() - a.length());
}
else
{
return (countDistinct(a) -
countDistinct(b));
}
}
});
// Print result
printArraystring(arr, n);
}
}
// This code is contributed by offbeat
Python3
# Python3 program of the above approach
import functools
# Function to return no of
# unique character in a word
def countDistinct(s):
# Initialize dictionary
m = {}
for i in range(len(s)):
# Count distinct characters
if s[i] not in m:
m[s[i]] = 1
else:
m[s[i]] += 1
return len(m)
# Function to perform sorting
def compare(a, b):
if (countDistinct(a) == countDistinct(b)):
# Check if size of string 1
# is same as string 2 then
# return false because s1 should
# not be placed before s2
return (len(b) - len(a))
else:
return (countDistinct(a) - countDistinct(b))
# Driver Code
arr = [ "Bananas", "do", "not",
"grow", "in","Mississippi" ]
n = len(arr)
# Print result
print(*sorted(
arr, key = functools.cmp_to_key(compare)), sep = ' ')
# This code is contributed by avanitrachhadiya2155
C#
// C# program of the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// Function to return no of
// unique character in a word
static int countDistinct(string s)
{
// Initialize map
Dictionary<char,
int> m = new Dictionary<char,
int>();
for(int i = 0; i < s.Length; i++)
{
// Count distinct characters
if (m.ContainsKey(s[i]))
{
m[s[i]]++;
}
else
{
m[s[i]] = 1;
}
}
return m.Count;
}
static int compare(string s1, string s2)
{
if (countDistinct(s1) == countDistinct(s2))
{
// Check if size of string 1
// is same as string 2 then
// return false because s1 should
// not be placed before s2
return s2.Length - s1.Length;
}
else
{
return (countDistinct(s1) -
countDistinct(s2));
}
}
// Function to print the sorted array of string
static void printArraystring(string []str, int n)
{
for(int i = 0; i < n; i++)
{
Console.Write(str[i] + " ");
}
}
// Driver Code
public static void Main(string[] args)
{
string []arr = { "Bananas", "do",
"not", "grow",
"in", "Mississippi" };
int n = arr.Length;
// Function call
Array.Sort(arr, compare);
// Print result
printArraystring(arr, n);
}
}
// This code is contributed by rutvik_56
JavaScript
// Javascript program for above approach
// function to return number of
// unique character in a word
function countDistinct(string){
// Initialize map
let obj = {};
for(let i = 0; i < string.length; i++){
// count distinct characters
if(string[i] in obj){
obj[string[i]] += 1;
}
else{
obj[string[i]] = 1;
}
}
let cnt = 0;
for(ele in obj) cnt++;
return cnt;
}
// Function to perform sorting
function compare(s1, s2){
if(countDistinct(s1) == countDistinct(s2)){
return (s2.length-s1.length);
}
else{
return (countDistinct(s1) - countDistinct(s2));
}
}
// Function to print the sorted Array of string
function printArraytString(str){
console.log(str.join(" "));
}
// Driver code
array1 = ["Bananas", "do","not", "grow", "in","Mississippi"];
// function call
array1.sort(compare);
// print resultant Array
printArraytString(array1)
// This code is contributed by Aditya Sharma
Outputdo in not Mississippi Bananas grow
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
Similar Reads
Count of substrings having all distinct characters Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
7 min read
Sort an array of strings in increasing order of sum of ASCII values of characters Given an array arr[] consisting of N strings, the task is to sort the strings in increasing order of the sum of the ASCII (American Standard Code for Information Interchange) value of their characters. Examples: Input: arr[] = {"for", "geeks", "app", "best"}Output: app for best geeksExplanation:Sum
7 min read
Count substrings made up of a single distinct character Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
5 min read
Print all distinct characters of a string in order (3 Methods) Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is âGeeks for Geeksâ, then output should be 'for' and if input string is âGeeks Quizâ, then output should be âGksQuizâ.The distinct characters should be printed in same order as they appear in
14 min read
Count of distinct permutation of a String obtained by swapping only unequal characters Given a string find the number of unique permutations that can be obtained by swapping two indices such that the elements at these indices are distinct. NOTE: Swapping is always performed in the original string. Examples: Input: str = "sstt"Output: 5Explanation: Swap str[0] with str[2], string obtai
11 min read
Print the most occurring character in an array of strings Given an array arr[] of lowercase strings, the task is to print the most occurring character in the set of strings.Examples: Input: arr[] = {"animal", "zebra", "lion", "giraffe"} Output: a Explanation: The frequency of 'a' is 4 which is highest. Input: arr[] = {"aa", "bb", "cc", "bde"} Output: b App
5 min read
Sort an array of strings lexicographically based on prefix Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order. Examples: Input: arr[] = {"sun", "moon", "mock"}Â Outpu
7 min read
Count of distinct substrings of a string using Suffix Array Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples: Input : str = âababaâ Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa"Reco
15+ min read
Sort groups of numbers and characters separately in a String Given string str of alphanumeric characters, the task is to sort the similar group of consecutive characters separately and print the modified string i.e. all consecutive groups of digits and alphabetical characters will be sorted separately. Examples: Input: str = "121geeks21" Output: 112eegks12 Ex
6 min read
Count ways to partition a string such that both parts have equal distinct characters Content has been removed on Author's request.
1 min read