Sort an array of strings based on count of distinct characters
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++
#include <bits/stdc++.h>
using namespace std;
int countDistinct(string s)
{
unordered_map< char , int > m;
for ( int i = 0; i < s.length(); i++) {
m[s[i]]++;
}
return m.size();
}
bool compare(string& s1, string& s2)
{
if (countDistinct(s1) == countDistinct(s2)) {
if (s1.size() == s2.size()) {
return false ;
}
return s1.size() > s2.size();
}
return countDistinct(s1) < countDistinct(s2);
}
void printArraystring(string str[], int n)
{
for ( int i = 0; i < n; i++)
cout << str[i] << " " ;
}
int main()
{
string arr[] = { "Bananas" , "do" ,
"not" , "grow" , "in" ,
"Mississippi" };
int n = sizeof (arr)
/ sizeof (arr[0]);
sort(arr, arr + n, compare);
printArraystring(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countDistinct(String s)
{
Map<Character, Integer> m = new HashMap<>();
for ( int i = 0 ; i < s.length(); i++)
{
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();
}
static void printArraystring(String[] str,
int n)
{
for ( int i = 0 ; i < n; i++)
{
System.out.print(str[i] + " " );
}
}
public static void main(String[] args)
{
String[] arr = { "Bananas" , "do" ,
"not" , "grow" ,
"in" , "Mississippi" };
int n = arr.length;
Arrays.sort(arr, new Comparator<String>()
{
public int compare(String a, String b)
{
if (countDistinct(a) ==
countDistinct(b))
{
return (b.length() - a.length());
}
else
{
return (countDistinct(a) -
countDistinct(b));
}
}
});
printArraystring(arr, n);
}
}
|
Python3
import functools
def countDistinct(s):
m = {}
for i in range ( len (s)):
if s[i] not in m:
m[s[i]] = 1
else :
m[s[i]] + = 1
return len (m)
def compare(a, b):
if (countDistinct(a) = = countDistinct(b)):
return ( len (b) - len (a))
else :
return (countDistinct(a) - countDistinct(b))
arr = [ "Bananas" , "do" , "not" ,
"grow" , "in" , "Mississippi" ]
n = len (arr)
print ( * sorted (
arr, key = functools.cmp_to_key(compare)), sep = ' ' )
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static int countDistinct( string s)
{
Dictionary< char ,
int > m = new Dictionary< char ,
int >();
for ( int i = 0; i < s.Length; i++)
{
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))
{
return s2.Length - s1.Length;
}
else
{
return (countDistinct(s1) -
countDistinct(s2));
}
}
static void printArraystring( string []str, int n)
{
for ( int i = 0; i < n; i++)
{
Console.Write(str[i] + " " );
}
}
public static void Main( string [] args)
{
string []arr = { "Bananas" , "do" ,
"not" , "grow" ,
"in" , "Mississippi" };
int n = arr.Length;
Array.Sort(arr, compare);
printArraystring(arr, n);
}
}
|
Javascript
function countDistinct(string){
let obj = {};
for (let i = 0; i < string.length; i++){
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 compare(s1, s2){
if (countDistinct(s1) == countDistinct(s2)){
return (s2.length-s1.length);
}
else {
return (countDistinct(s1) - countDistinct(s2));
}
}
function printArraytString(str){
console.log(str.join( " " ));
}
array1 = [ "Bananas" , "do" , "not" , "grow" , "in" , "Mississippi" ];
array1.sort(compare);
printArraytString(array1)
|
Output
do in not Mississippi Bananas grow
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
Last Updated :
21 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...