Open In App

Check whether count of distinct characters in a string is Prime or not

Given a string of lowercase English alphabets. The task is to check if the count of distinct characters in the string is prime or not.

Examples: 



Input : str = "geeksforgeeks"
Output :Yes
Explanation: The number of distinct characters in the
string is 7, and 7 is a prime number.

Input : str ="geeks"
Output : No 

In this problem first we have to count the distinct characters in the string. We will use a map to store the frequency of each alphabets. The next step is to count the number of distinct characters, and check whether the number is prime or not . 

If the number is prime we will print Yes, else No. 



Below is the implementation of the above approach:  




// C++ program to check whether count of
// distinct characters in a string
// is Prime or not
#include <bits/stdc++.h>
using namespace std;
 
// Find whether a number is prime or not
bool isPrime(int n)
{
    int i;
 
    // 1 is not prime
    if (n == 1)
        return false;
 
    // check if there is any factor or not
    for (i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Count the distinct characters in a string
int countDistinct(string s)
{
    // create a map to store the
    // frequency of characters
    unordered_map<char, int> m;
 
    // traverse the string
    for (int i = 0; i < s.length(); i++) {
        // increase the frequency of character
        m[s[i]]++;
    }
 
    return m.size();
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
 
    if (isPrime(countDistinct(str)))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    return 0;
}




// Java program to check whether count of
// distinct characters in a string
// is Prime or not
import java.util.*;
 
class GFG
{
    // Find whether a number is prime or not
    static boolean isPrime(int n)
    {
        int i;
     
        // 1 is not prime
        if (n == 1)
            return false;
     
        // check if there is any factor or not
        for (i = 2; i <= Math.sqrt(n); i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }
     
    // Count the distinct characters in a string
    static int countDistinct(String s)
    {
        // create a map to store the
        // frequency of characters
        Set<Character> m = new HashSet<Character>();
     
        // traverse the string
        for (int i = 0; i < s.length(); i++)
        {
             
            // increase the frequency of character
            m.add(s.charAt(i));
             
        }
         
        return m.size();
    }
     
    // Driver code
    public static void main(String []args)
    {
        String str = "geeksforgeeks";
     
        if (isPrime(countDistinct(str)))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by ihritik




# Python 3 program to check whether
# count of distinct characters in a
# string is Prime or not
 
# from math library import
# sqrt method
from math import sqrt
 
# Find whether a number
# is prime or not
def isPrime(n) :
 
    # 1 is not prime
    if n == 1 :
        return False
 
    # check if there is any
    # factor or not
    for i in range(2, int(sqrt(n)) + 1) :
 
        if n % i == 0 :
            return False
 
    return True
 
# Count the distinct characters
# in a string
def countDistinct(s) :
 
    # create a dictionary to store
    # the frequency of characters
    m = {}
 
    # dictionary with keys and its
    # initialize with value 0
    m = m.fromkeys(s, 0)
 
    # traverse the string
    for i in range(len(s)) :
 
        # increase the frequency
        # of character
        m[s[i]] += 1
 
    return len(m.keys())
 
# Driver code    
if __name__ == "__main__" :
 
    str = "geeksforgeeks"
 
    if isPrime(countDistinct(str)) :
        print("Yes")
    else :
        print("No")
         
# This code is contributed
# by ANKITRAI1




// C# program to check whether count of
// distinct characters in a string
// is Prime or not
using System;
using System.Collections.Generic;
 
class GFG
{
    // Find whether a number is prime or not
    static bool isPrime(int n)
    {
        int i;
     
        // 1 is not prime
        if (n == 1)
            return false;
     
        // check if there is any factor or not
        for (i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }
     
    // Count the distinct characters in a string
    static int countDistinct(String s)
    {
        // create a map to store the
        // frequency of characters
        HashSet<char> m = new HashSet<char>();
     
        // traverse the string
        for (int i = 0; i < s.Length; i++)
        {
             
            // increase the frequency of character
            m.Add(s[i]);
             
        }
         
        return m.Count;
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String str = "geeksforgeeks";
     
        if (isPrime(countDistinct(str)))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code has been contributed by 29AjayKumar




<script>
 
// Javascript program to check whether count of
// distinct characters in a string
// is Prime or not
 
// Find whether a number is prime or not
function isPrime(n)
{
    var i;
 
    // 1 is not prime
    if (n == 1)
        return false;
 
    // check if there is any factor or not
    for (i = 2; i <= Math.sqrt(n); i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Count the distinct characters in a string
function countDistinct(s)
{
    // create a map to store the
    // frequency of characters
    var m = new Map();
 
    // traverse the string
    for (var i = 0; i < s.length; i++) {
        // increase the frequency of character
        if(m.has(s[i]))
        {
            m.set(s[i], m[s[i]]+1);
        }
        else
        {
            m.set(s[i],1);
        }
    }
 
    return m.size;
}
 
// Driver code
var str = "geeksforgeeks";
if (isPrime(countDistinct(str)))
    document.write( "Yes" );
else
    document.write( "No" );
 
// This code is contributed by rutvik_56.
</script>

Output
Yes

Complexity Analysis:

Method 2: Using Counter function:

Below is the implementation:




// Cpp program for the above approach
#include <iostream>
#include <unordered_map>
#include <cmath>
 
using namespace std;
 
bool isPrime(int n) {
    if (n == 1) { // 1 is not prime
        return false;
    }
 
    // Check if there is any factor or not
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
 
    return true;
}
 
bool countDis(string str) {
 
    // Stores all frequencies
    unordered_map<char, int> freq;
 
    for (int i = 0; i < str.length(); i++) {
        char ch = str[i];
        freq[ch]++;
    }
 
    // Return the size of the freq object
    if (isPrime(freq.size())) {
        return true;
    } else {
        return false;
    }
}
 
// Driver code
int main() {
    string S = "geeksforgeeks";
    cout << countDis(S) << endl;
    return 0;
}
 
 
//This code is contributed by shivamsharma215
//Output is 1 i.e. True




import java.util.*;
 
public class Main {
    public static boolean isPrime(int n) {
        if (n == 1) { // 1 is not prime
            return false;
        }
 
        // Check if there is any factor or not
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
 
        return true;
    }
 
    public static boolean countDis(String str) {
 
        // Stores all frequencies
        Map<Character, Integer> freq = new HashMap<>();
 
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);
        }
 
        // Return the size of the freq object
        if (isPrime(freq.keySet().size())) {
            return true;
        } else {
            return false;
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        String S = "geeksforgeeks";
        System.out.println(countDis(S));
    }
}




# Python program for the above approach
from collections import Counter
from math import sqrt as sqrt
 
 
def isPrime(n):
 
    # 1 is not prime
    if n == 1:
        return False
 
    # check if there is any
    # factor or not
    for i in range(2, int(sqrt(n)) + 1):
 
        if n % i == 0:
            return False
 
    return True
 
# Function to count the number of distinct
# characters present in the string
# str and check whether it is prime
 
 
def countDis(str):
 
    # Stores all frequencies
    freq = Counter(str)
 
    # Return the size of the freq dictionary
    if(isPrime(len(freq))):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
        # Given string S
    S = "geeksforgeeks"
 
    print(countDis(S))
 
# This code is contributed by vikkycirus




using System;
using System.Collections.Generic;
using System.Linq;
 
public class Gfg
{
    public static bool isPrime(int n)
    {
        if (n == 1) // 1 is not prime
        {
            return false;
        }
 
        // Check if there is any factor or not
        for (int i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
 
        return true;
    }
 
    public static bool countDis(string str)
    {
        // Stores all frequencies
        Dictionary<char, int> freq = new Dictionary<char, int>();
 
        foreach (char ch in str)
        {
            if (freq.ContainsKey(ch))
            {
                freq[ch]++;
            }
            else
            {
                freq.Add(ch, 1);
            }
        }
 
        // Return the size of the freq object
        if (isPrime(freq.Count))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
 
    public static void Main()
    {
        string S = "geeksforgeeks";
        Console.WriteLine(countDis(S));
    }
}




// Javacript program for the above approach
function isPrime(n) {
  if (n === 1) { // 1 is not prime
    return false;
  }
 
  // Check if there is any factor or not
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) {
      return false;
    }
  }
 
  return true;
}
 
function countDis(str)
{
 
  // Stores all frequencies
  let freq = {};
 
  for (let i = 0; i < str.length; i++) {
    freq[str[i]] = (freq[str[i]] || 0) + 1;
  }
 
  // Return the size of the freq object
  if (isPrime(Object.keys(freq).length)) {
    return true;
  } else {
    return false;
  }
}
 
// Driver code
let S = "geeksforgeeks";
console.log(countDis(S));
 
// This code is contributed by codebraxnzt

Output
True

Article Tags :