Count of anagrams of each string in an array present in another array
Last Updated :
29 Oct, 2023
Given two arrays arr1[] and arr2[] consisting of strings, the task is to print the count of anagrams of every string in arr2[] that are present in arr1[].
Examples:
Input: arr1[] = [“geeks”, “learn”, “for”, “egeks”, “ealrn”], arr2[] = [“kgees”, “rof”, “nrael”]
Output: 2 1 2
Explanation:
Anagrams of arr2[0] (“kgees”) in arr1 : “geeks” and “egeks”.
Anagrams of arr2[1] (“rof”) in arr1 : “for”.
Anagrams of arr2[2] (“nrael”) in arr1 : “learn” and “ealrn”.
Input: arr1[] = [“code”, “to”, “grow”, “odce”], arr2[] = [“edoc”, “wgor”, “ot”]
Output: 2 1 1
Explanation:
Anagrams of arr2[0] (“edoc”) in arr1 “code” and “odce”.
Anagrams of arr2[1] (“wgor”) in arr1 “grow”.
Anagrams of arr2[2] (“ot”) in arr1 “to”
Approach:
To solve the problem, the idea is to use frequency-counting with the help of HashMap. Store the frequencies of every string in arr1[] in hashmap in their sorted form. Traverse arr2[], sort strings in arr2[], and print their respective frequencies in HashMap.
Below is the implementation of the above approach:
C++
Java
import java.util.*;
class GFG{
static String sortString(String inputString)
{
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static void count(String arr1[],
String arr2[],
int n, int m)
{
HashMap<String, Integer> freq = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
arr1[i] = sortString(arr1[i]);
if (freq.containsKey(arr1[i]))
{
freq.put(arr1[i],
freq.get(arr1[i]) + 1 );
}
else
{
freq.put(arr1[i], 1 );
}
}
for ( int i = 0 ; i < m; i++)
{
arr2[i] = sortString(arr2[i]);
System.out.print(freq.get(arr2[i]) + " " );
}
}
public static void main(String[] args)
{
String arr1[] = { "geeks" , "learn" ,
"for" , "egeks" ,
"ealrn" };
int n = arr1.length;
String arr2[] = { "kgees" , "rof" ,
"nrael" };
int m = arr2.length;
count(arr1, arr2, n, m);
}
}
|
Python3
def count(arr1, arr2, n, m):
freq = {}
for word in arr1:
word = ' ' .join( sorted (word))
if word in freq.keys():
freq[word] = freq[word] + 1
else :
freq[word] = 1
for word in arr2:
word = ' ' .join( sorted (word))
if word in freq.keys():
print (freq[word], end = " " )
else :
print ( 0 , end = " " )
print ()
if __name__ = = '__main__' :
arr1 = [ "geeks" , "learn" , "for" ,
"egeks" , "ealrn" ]
n = len (arr1)
arr2 = [ "kgees" , "rof" , "nrael" ]
m = len (arr2)
count(arr1, arr2, n, m)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static String sortString(String inputString)
{
char []tempArray = inputString.ToCharArray();
Array.Sort(tempArray);
return new String(tempArray);
}
static void count(String []arr1,
String []arr2,
int n, int m)
{
Dictionary<String,
int > freq = new Dictionary<String,
int >();
for ( int i = 0; i < n; i++)
{
arr1[i] = sortString(arr1[i]);
if (freq.ContainsKey(arr1[i]))
{
freq[arr1[i]] =
freq[arr1[i]] + 1;
}
else
{
freq.Add(arr1[i], 1);
}
}
for ( int i = 0; i < m; i++)
{
arr2[i] = sortString(arr2[i]);
Console.Write(freq[arr2[i]] + " " );
}
}
public static void Main(String[] args)
{
String []arr1 = { "geeks" , "learn" ,
"for" , "egeks" ,
"ealrn" };
int n = arr1.Length;
String []arr2 = { "kgees" , "rof" ,
"nrael" };
int m = arr2.Length;
count(arr1, arr2, n, m);
}
}
|
Javascript
<script>
function sortString(inputString)
{
let tempArray = inputString.split( '' );
tempArray.sort();
return tempArray.join( "" );
}
function count(arr1, arr2, n, m)
{
let freq = new Map();
for (let i = 0; i < n; i++)
{
arr1[i] = sortString(arr1[i]);
if (freq.has(arr1[i]))
{
freq.set(arr1[i],
freq.get(arr1[i]) + 1);
}
else
{
freq.set(arr1[i], 1);
}
}
for (let i = 0; i < m; i++)
{
arr2[i] = sortString(arr2[i]);
document.write(freq.get(arr2[i]) + " " );
}
}
let arr1 = [ "geeks" , "learn" ,
"for" , "egeks" ,
"ealrn" ];
let n = arr1.length;
let arr2 = [ "kgees" , "rof" ,
"nrael" ];
let m = arr2.length;
count(arr1, arr2, n, m);
</script>
|
Time Complexity: O(n*plog(p)+m*qlog(q)) where n and m are the sizes of both the array and p and q are the maximum size of string present in arr1 and arr2 respectively.
Auxiliary space: O(n+m).
Another Approach:
- Create a helper function “calculateFrequency” that takes a string and an integer array of size 26 as input. The function should iterate over the string and increment the frequency of each character in the integer array. For example, if the string is “geeks”, the frequency array should be [1, 0, 0, 0, 2, 0, 0, …, 0] because there is one ‘g’, two ‘e’s, one ‘k’, and one ‘s’.
- Create a function “checkAnagram” that takes two strings as input and returns true if they are anagrams of each other. To check if two strings are anagrams, we can use the “calculateFrequency” function to calculate the frequency arrays for both strings and compare them.
- Create a function “countAnagrams” that takes a string and an array of strings as input and returns the number of strings in the array that are anagrams of the given string. The function should iterate over the array and use the “checkAnagram” function to check if each string is an anagram of the given string.
- In the main function, create two arrays of strings “arr1” and “arr2” and their sizes “n1” and “n2” respectively. Iterate over the strings in “arr2” and call the “countAnagrams” function to count the number of anagrams of each string in “arr1”. Print the count for each string in “arr2”.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void calculateFrequency(string str, int *freq) {
for ( int i=0; i<str.length(); i++)
freq[str[i] - 'a' ]++;
}
bool checkAnagram(string str1, string str2) {
int freq1[26] = {0}, freq2[26] = {0};
calculateFrequency(str1, freq1);
calculateFrequency(str2, freq2);
for ( int i=0; i<26; i++)
if (freq1[i] != freq2[i])
return false ;
return true ;
}
int countAnagrams(string str, string *arr, int n) {
int count = 0;
for ( int i=0; i<n; i++)
if (checkAnagram(str, arr[i]))
count++;
return count;
}
void printAnagramCount(string *arr1, int n1, string *arr2, int n2) {
for ( int i=0; i<n2; i++) {
int count = countAnagrams(arr2[i], arr1, n1);
cout<<count<< " " ;
}
}
int main() {
string arr1[] = { "geeks" , "learn" , "for" , "egeks" , "ealrn" };
string arr2[] = { "kgees" , "rof" , "nrael" };
int n1 = sizeof (arr1)/ sizeof (arr1[0]);
int n2 = sizeof (arr2)/ sizeof (arr2[0]);
printAnagramCount(arr1, n1, arr2, n2);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
public static void calculateFrequency(String str, int [] freq) {
for ( int i = 0 ; i < str.length(); i++)
freq[str.charAt(i) - 'a' ]++;
}
public static boolean checkAnagram(String str1, String str2) {
int [] freq1 = new int [ 26 ];
int [] freq2 = new int [ 26 ];
calculateFrequency(str1, freq1);
calculateFrequency(str2, freq2);
return Arrays.equals(freq1, freq2);
}
public static int countAnagrams(String str, String[] arr, int n) {
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (checkAnagram(str, arr[i]))
count++;
}
return count;
}
public static void printAnagramCount(String[] arr1, int n1, String[] arr2, int n2) {
for ( int i = 0 ; i < n2; i++) {
int count = countAnagrams(arr2[i], arr1,n1);
System.out.print(count + " " );
}
}
public static void main(String[] args) {
String[] arr1 = { "geeks" , "learn" , "for" , "egeks" , "ealrn" };
String[] arr2 = { "kgees" , "rof" , "nrael" };
int n1 = arr1.length;
int n2 = arr2.length;
printAnagramCount(arr1, n1, arr2, n2);
}
}
|
Python3
def calculateFrequency(s):
freq = [ 0 ] * 26
for char in s:
freq[ ord (char) - ord ( 'a' )] + = 1
return freq
def checkAnagram(str1, str2):
freq1 = calculateFrequency(str1)
freq2 = calculateFrequency(str2)
return freq1 = = freq2
def countAnagrams(s, arr):
count = 0
for item in arr:
if checkAnagram(s, item):
count + = 1
return count
def printAnagramCount(arr1, arr2):
for item in arr2:
count = countAnagrams(item, arr1)
print (count, end = " " )
arr1 = [ "geeks" , "learn" , "for" , "egeks" , "ealrn" ]
arr2 = [ "kgees" , "rof" , "nrael" ]
printAnagramCount(arr1, arr2)
|
C#
using System;
class Program
{
static void CalculateFrequency( string str, int [] freq)
{
foreach ( char c in str)
{
freq++;
}
}
static bool CheckAnagram( string str1, string str2)
{
int [] freq1 = new int [26];
int [] freq2 = new int [26];
CalculateFrequency(str1, freq1);
CalculateFrequency(str2, freq2);
for ( int i = 0; i < 26; i++)
{
if (freq1[i] != freq2[i])
{
return false ;
}
}
return true ;
}
static int CountAnagrams( string str, string [] arr)
{
int count = 0;
foreach ( string s in arr)
{
if (CheckAnagram(str, s))
{
count++;
}
}
return count;
}
static void PrintAnagramCount( string [] arr1, string [] arr2)
{
foreach ( string s2 in arr2)
{
int count = CountAnagrams(s2, arr1);
Console.Write(count + " " );
}
}
static void Main()
{
string [] arr1 = { "geeks" , "learn" , "for" , "egeks" , "ealrn" };
string [] arr2 = { "kgees" , "rof" , "nrael" };
PrintAnagramCount(arr1, arr2);
}
}
|
Javascript
function calculateFrequency(str, freq) {
for (let i = 0; i < str.length; i++) {
freq[str.charCodeAt(i) - 'a' .charCodeAt(0)]++;
}
}
function checkAnagram(str1, str2) {
const freq1 = new Array(26).fill(0);
const freq2 = new Array(26).fill(0);
calculateFrequency(str1, freq1);
calculateFrequency(str2, freq2);
for (let i = 0; i < 26; i++) {
if (freq1[i] !== freq2[i]) {
return false ;
}
}
return true ;
}
function countAnagrams(str, arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (checkAnagram(str, arr[i])) {
count++;
}
}
return count;
}
function printAnagramCount(arr1, arr2) {
for (let i = 0; i < arr2.length; i++) {
const count = countAnagrams(arr2[i], arr1);
console.log(count + " " );
}
}
const arr1 = [ "geeks" , "learn" , "for" , "egeks" , "ealrn" ];
const arr2 = [ "kgees" , "rof" , "nrael" ];
printAnagramCount(arr1, arr2);
|
Time Complexity: The time complexity of the given code is O(n1n2k), where “n1” is the size of “arr1”, “n2” is the size of “arr2” and “k” is the maximum length of a string in the arrays. This is because the main function calls the “printAnagramCount” function which uses a nested loop to iterate through each string in “arr2″and then for each string, it calls the “countAnagrams” function which has another nested loop to iterate through each string in “arr1”.
Auxiliary Space: The space complexity of the given code is O(k), where “k” is the maximum length of a string in the arrays. This is because the “calculateFrequency” function uses two arrays of size 26 (for each character in the alphabet) to store the frequency of characters in a string. Since the size of these arrays is constant, the space complexity of the code is proportional to the maximum length of a string in the arrays.
Please suggest if someone has a better solution that is more efficient in terms of space and time.
This article is contributed by Aarti_Rathi.
Share your thoughts in the comments
Please Login to comment...