Check if characters of a given string can be used to form any N equal strings

Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No.

Examples:

Input: S = “caacbb”, N = 2
Output: Yes
Explanation: All possible strings that can be generated N(= 2) times are {“abc”, “ab”, “aa”, “bb”, “cc”, “bc”, “ca”}

Input: S = “cbacbac”, N = 3
Output: No
Explanation: Since none of the characters occurs N times, therefore no string can be generated N times from the characters of the given string.

Naive Approach: The simplest approach to solve the problem is to generate all possible permutations of all possible lengths of the given string and check if any permutation occurs N times or not. If found to be true, print “Yes”. Otherwise, print “No”



Time Complexity: O(N*L!), where L is the length of the given string.
Auxiliary Space: O(L)

Efficient Approach: The idea is to store the frequency of all characters and count the number of characters occurring at least N times. Follow the steps below to solve the problem:

  1. Store the frequencies of each character of the string in an array, say freq[].
  2. Traverse the freq[] array and for every ith Character, check if freq[i] >= N or not.
  3. If any character is found to be satisfying the above condition, print Yes. Otherwise, print No.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the freq of
// any charcater is divisible by N
bool isSame(string str, int n)
{
    // Stores the frequency of characters
    map<int, int> mp;
 
    for (int i = 0; i < str.length(); i++) {
        mp[str[i] - 'a']++;
    }
 
    for (auto it : mp) {
 
        // If frequency of a character
        // is not divisible by n
        if ((it.second) >= n) {
            return true;
        }
    }
 
    // If no character has frequency
    // at least N
    return false;
}
 
// Driver Code
int main()
{
    string str = "ccabcba";
    int n = 4;
 
    // Function Call
    if (isSame(str, n)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to check if the freq of
// any charcater is divisible by N
static boolean isSame(String str, int n)
{
    // Stores the frequency of characters
    HashMap<Integer,
            Integer> mp = new HashMap<Integer,
                                      Integer>();
 
    for (int i = 0; i < str.length(); i++)
    {
        if(mp.containsKey(str.charAt(i) - 'a'))
        {
            mp.put(str.charAt(i) - 'a',
                   mp.get(str.charAt(i) - 'a') + 1);
        }
          else
        {
            mp.put(str.charAt(i) - 'a', 1);
        }
    }
 
    for (Map.Entry<Integer, Integer> it : mp.entrySet())
    {
        // If frequency of a character
        // is not divisible by n
        if ((it.getValue()) >= n)
        {
            return true;
        }
    }
 
    // If no character has frequency
    // at least N
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "ccabcba";
    int n = 4;
 
    // Function Call
    if (isSame(str, n))
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
from collections import defaultdict
 
# Function to check if the freq of
# any charcater is divisible by N
def isSame(str, n):
 
    # Stores the frequency of characters
    mp = defaultdict(lambda : 0)
 
    for i in range(len(str)):
        mp[ord(str[i]) - ord('a')] += 1
 
    for it in mp.keys():
 
        # If frequency of a character
        # is not divisible by n
        if(mp[it] >= n):
            return True
             
    # If no character has frequency
    # at least N
    return False
 
# Driver Code
str = "ccabcba"
n = 4
 
# Function call
if(isSame(str, n)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to check if the freq of
// any charcater is divisible by N
static bool isSame(String str, int n)
{
    // Stores the frequency of characters
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
 
    for (int i = 0; i < str.Length; i++)
    {
        if(mp.ContainsKey(str[i] - 'a'))
        {
            mp[str[i] - 'a'] =
                   mp[str[i] - 'a'] + 1;
        }
          else
        {
            mp.Add(str[i] - 'a', 1);
        }
    }
 
    foreach (KeyValuePair<int,
                          int> it in mp)
    {
        // If frequency of a character
        // is not divisible by n
        if ((it.Value) >= n)
        {
            return true;
        }
    }
 
    // If no character has frequency
    // at least N
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "ccabcba";
    int n = 4;
 
    // Function Call
    if (isSame(str, n))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


 
 

Output: 

No




 

Time Complexity: O(L), where L is the length of the given string
Auxiliary Space: O(L) 

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 Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.