Check if characters of a given string can be used to form any N equal strings
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:
- Store the frequencies of each character of the string in an array, say freq[].
- Traverse the freq[] array and for every ith Character, check if freq[i] >= N or not.
- 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 <bits/stdc++.h>
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<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
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
<script>
// JavaScript program for the above approach
// Function to check if the freq of
// any character is divisible by N
function isSame(str, n)
{
// Stores the frequency of characters
var mp = {};
for(var i = 0; i < str.length; i++)
{
if (mp.hasOwnProperty(str[i].charCodeAt(0) -
"a".charCodeAt(0)))
{
mp[str[i].charCodeAt(0) - "a".charCodeAt(0)] =
mp[str[i].charCodeAt(0) - "a".charCodeAt(0)] + 1;
} else
{
mp[str[i].charCodeAt(0) -
"a".charCodeAt(0)] = 1;
}
}
for(const [key, value] of Object.entries(mp))
{
// If frequency of a character
// is not divisible by n
if (value >= n)
{
return true;
}
}
// If no character has frequency
// at least N
return false;
}
// Driver Code
var str = "ccabcba";
var n = 4;
// Function Call
if (isSame(str, n))
{
document.write("Yes");
}
else
{
document.write("No");
}
// This code is contributed by rdtank
</script>
Time Complexity: O(L), where L is the length of the given string
Auxiliary Space: O(L)
Similar Reads
Check if a two character string can be made using given words Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[
6 min read
Check if a string can be split into two strings with same number of K-frequent characters Given a string S and an integer K, the task is to check if it is possible to distribute these characters into two strings such that the count of characters having a frequency K in both strings is equal. If it is possible, then print a sequence consisting of 1 and 2, which denotes which character sho
11 min read
Check if two strings can be made equal by swapping pairs of adjacent characters Given two strings A and B of length N and M respectively and an array arr[] consisting of K integers, the task is to check if the string B can be obtained from the string A by swapping any pair of adjacent characters of the string A any number of times such that the swapped indices are not present i
15+ min read
Check if a string can be converted to another by swapping of adjacent characters of given type Given two strings str1 and str2 of size N consisting of only three characters A, B, and C, the task is to check whether the string str1 can be changed to str2 using the below operations: Replacing one occurrence of âBCâ with âCBâ i.e swap adjacent âBâ and âCâ.Replacing one occurrence of âCAâ with âA
7 min read
Check if a string can be made equal to another string by swapping or replacement of characters Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = âabcâ, S2 = â
8 min read
Total length of string from given Array of strings composed using given characters Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.Examples: Input: string = ["mouse", "me", "bat", "lion"], chars = "eusamotb" Output: 10 Explanation: The strings that can be formed using t
6 min read
Check whether second string can be formed from characters of first string Given two strings str1 and str2, check if str2 can be formed from str1 Example : Input : str1 = geekforgeeks, str2 = geeksOutput : YesHere, string2 can be formed from string1. Input : str1 = geekforgeeks, str2 = andOutput : NoHere string2 cannot be formed from string1. Input : str1 = geekforgeeks, s
5 min read
Check if two strings after processing backspace character are equal or not Given two strings s1 and s2, let us assume that while typing the strings there were some backspaces encountered which are represented by #. The task is to determine whether the resultant strings after processing the backspace character would be equal or not. Examples: Input: s1= geee#e#ks, s2 = gee#
8 min read
Check if Strings can be made equal by interchanging Characters Given an array of N strings, the task is to find if it is possible to make all the strings equal by performing the following operations: Remove a character from ith string and insert it in an arbitrary position in jth string. (i and j can be the same)You may perform this operation any number of time
7 min read
Program to check if first and the last characters of string are equal We are given a string, we need to check whether the first and last characters of the string str are equal or not. Case sensitivity is to be considered. Examples : Input : university Output : Not Equal Explanation: In the string "university", the first character is 'u' and the last character is 'y',
4 min read