 Open in App
Not now

# Count of anagrams of each string in an array present in another array

• Difficulty Level : Easy
• Last Updated : 22 Jul, 2022

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 (“kgees”) in arr1 : “geeks” and “egeks”.
Anagrams of arr2 (“rof”) in arr1 : “for”.
Anagrams of arr2 (“nrael”) in arr1 : “learn” and “ealrn”.

Input: arr1[] = [“code”, “to”, “grow”, “odce”], arr2[] = [“edoc”, “wgor”, “ot”]
Output: 2 1 1
Explanation:
Anagrams of arr2 (“edoc”) in arr1 “code” and “odce”.
Anagrams of arr2 (“wgor”) in arr1 “grow”.
Anagrams of arr2 (“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++

 `// C++ Program to count the``// number of anagrams of``// each string in a given``// array present in``// another array` `#include ``using` `namespace` `std;` `// Function to return the``// count of anagrams``void` `count(string arr1[],``           ``string arr2[],``           ``int` `n, ``int` `m)``{``    ``// Store the frequencies``    ``// of strings in arr1[]``    ``unordered_map freq;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Sort the string``        ``sort(arr1[i].begin(),``             ``arr1[i].end());` `        ``// Increase its frequency``        ``// in the map``        ``freq[arr1[i]]++;``    ``}` `    ``for` `(``int` `i = 0; i < m; i++) {` `        ``// Sort the string``        ``sort(arr2[i].begin(),``             ``arr2[i].end());` `        ``// Display its anagrams``        ``// in arr1[]``        ``cout << freq[arr2[i]]``             ``<< ``" "``;``    ``}``}` `// Driver Code``int` `main()``{` `    ``string arr1[] = { ``"geeks"``, ``"learn"``,``                      ``"for"``, ``"egeks"``,``                      ``"ealrn"` `};``    ``int` `n = ``sizeof``(arr1)``            ``/ ``sizeof``(string);` `    ``string arr2[] = { ``"kgees"``, ``"rof"``,``                      ``"nrael"` `};``    ``int` `m = ``sizeof``(arr2)``            ``/ ``sizeof``(string);` `    ``count(arr1, arr2, n, m);``}`

## Java

 `// Java program to count the number``// of anagrams of each String in a``// given array present in``// another array``import` `java.util.*;` `class` `GFG{` `static` `String sortString(String inputString)``{``    ` `    ``// Convert input string to char array``    ``char` `tempArray[] = inputString.toCharArray();``      ` `    ``// Sort tempArray``    ``Arrays.sort(tempArray);``      ` `    ``// Return new sorted string``    ``return` `new` `String(tempArray);``}` `// Function to return the``// count of anagrams``static` `void` `count(String arr1[],``                  ``String arr2[],``                  ``int` `n, ``int` `m)``{``    ` `    ``// Store the frequencies``    ``// of Strings in arr1[]``    ``HashMap freq = ``new` `HashMap<>();` `    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ` `        ``// Sort the String``        ``arr1[i] = sortString(arr1[i]);``        ` `        ``// Increase its frequency``        ``// in the map``        ``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++)``    ``{``        ` `        ``// Sort the String``        ``arr2[i] = sortString(arr2[i]);` `        ``// Display its anagrams``        ``// in arr1[]``        ``System.out.print(freq.get(arr2[i]) + ``" "``);``    ``}``}` `// Driver Code``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);``}``}` `// This code is contributed by Amit Katiyar`

## Python3

 `# Python3 program to count the number``# of anagrams of each string in a``# given array present in another array` `# Function to return the count of anagrams``def` `count(arr1, arr2, n, m):``    ` `    ``# Store the frequencies of``    ``# strings in arr1``    ``freq ``=` `{}` `    ``for` `word ``in` `arr1:``        ` `        ``# Sort the string``        ``word ``=` `' '``.join(``sorted``(word))` `        ``# Increase its frequency``        ``if` `word ``in` `freq.keys():``            ``freq[word] ``=` `freq[word] ``+` `1``        ``else``:``            ``freq[word] ``=` `1` `    ``for` `word ``in` `arr2:``        ` `        ``# Sort the string``        ``word ``=` `' '``.join(``sorted``(word))` `        ``# Display its anagrams``        ``# in arr1``        ``if` `word ``in` `freq.keys():``            ``print``(freq[word], end ``=` `" "``)``        ``else``:``            ``print``(``0``, end ``=` `" "``)``            ` `    ``print``()    ` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``     ` `    ``arr1 ``=` `[ ``"geeks"``, ``"learn"``, ``"for"``,``             ``"egeks"``, ``"ealrn"` `]``    ``n ``=` `len``(arr1)``    ` `    ``arr2 ``=` `[ ``"kgees"``, ``"rof"``, ``"nrael"` `]``    ``m ``=` `len``(arr2)` `    ``count(arr1, arr2, n, m)` `# This code is contributed by Pawan_29`

## C#

 `// C# program to count the number``// of anagrams of each String in a``// given array present in``// another array``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `static` `String sortString(String inputString)``{``    ` `    ``// Convert input string to char array``    ``char` `[]tempArray = inputString.ToCharArray();``      ` `    ``// Sort tempArray``    ``Array.Sort(tempArray);``      ` `    ``// Return new sorted string``    ``return` `new` `String(tempArray);``}` `// Function to return the``// count of anagrams``static` `void` `count(String []arr1,``                  ``String []arr2,``                  ``int` `n, ``int` `m)``{``    ` `    ``// Store the frequencies``    ``// of Strings in arr1[]``    ``Dictionary freq = ``new` `Dictionary();` `    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ` `        ``// Sort the String``        ``arr1[i] = sortString(arr1[i]);``        ` `        ``// Increase its frequency``        ``// in the map``        ``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++)``    ``{``        ` `        ``// Sort the String``        ``arr2[i] = sortString(arr2[i]);` `        ``// Display its anagrams``        ``// in arr1[]``        ``Console.Write(freq[arr2[i]] + ``" "``);``    ``}``}` `// Driver Code``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);``}``}` `// This code is contributed by Amit Katiyar`

## Javascript

 ``

Output:

`2 1 2`

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).

Please suggest if someone has a better solution that is more efficient in terms of space and time.