Related Articles

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

• Difficulty Level : Easy
• Last Updated : 30 Jun, 2021

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++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to check if the freq of``// any character 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"``;``    ``}``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``class` `GFG{` `// Function to check if the freq of``// any character is divisible by N``static` `boolean` `isSame(String str, ``int` `n)``{``    ``// Stores the frequency of characters``    ``HashMap mp = ``new` `HashMap();` `    ``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 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`

## Python3

 `# Python3 program for the above approach``from` `collections ``import` `defaultdict` `# Function to check if the freq of``# any character 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`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG{` `// Function to check if the freq of``// any character 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`

## Javascript

 ``
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. Participate in the Scholorship Test for First-Step-to-DSA Course for Class 9 to 12 students.

My Personal Notes arrow_drop_up
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}