Skip to content
Related Articles

Related Articles

Improve Article

Count Occurrences of Anagrams

  • Difficulty Level : Medium
  • Last Updated : 15 Jul, 2021

Given a word and a text, return the count of the occurrences of anagrams of the word in the text(For eg: anagrams of word for are for, ofr, rof etc.))

Examples: 

Input : forxxorfxdofr
        for
Output : 3
Explanation : Anagrams of the word for - for, orf, 
ofr appear in the text and hence the count is 3.

Input : aabaabaa
        aaba
Output : 4
Explanation : Anagrams of the word aaba - aaba, 
abaa each appear twice in the text and hence the
count is 4.

A simple approach is to traverse from start of the string considering substrings of length equal to the length of the given word and then check if this substring has all the characters of word.

C++




// A Simple C++ program to count anagrams of a
// pattern in a text.
#include<bits/stdc++.h>
using namespace std;
 
// Function to find if two strings are equal
bool areAnagram(string s1, string s2)
{
    map<char, int> m;
    for(int i = 0; i < s1.length(); i++)
        m[s1[i]]++;
         
    for(int i = 0; i < s2.length(); i++)
        m[s2[i]]--;
         
    for(auto it = m.begin(); it != m.end(); it++)
        if(it -> second != 0)
            return false;
             
        return true;
}
 
int countAnagrams(string text, string word)
{
     
    // Initialize result
    int res = 0;
    for(int i = 0;
            i < text.length() - word.length() + 1;
            i++)
    {
         
        // Check if the word and substring are
        // anagram of each other.
        if (areAnagram(text.substr(i, word.length()),
                                      word))
            res++;
    }
    return res;
}
 
// Driver Code
int main()
{
    string text = "forxxorfxdofr";
    string word = "for";
     
    cout << countAnagrams(text, word);
     
    return 0;
}
 
// This code is contributed by probinsah

Java




// A Simple Java program to count anagrams of a
// pattern in a text.
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Function to find if two strings are equal
    static boolean araAnagram(String s1,
                              String s2)
    {
        // converting strings to char arrays
        char[] ch1 = s1.toCharArray();
        char[] ch2 = s2.toCharArray();
 
        // sorting both char arrays
        Arrays.sort(ch1);
        Arrays.sort(ch2);
 
        // Check for equality of strings
        if (Arrays.equals(ch1, ch2))
            return true;
        else
            return false;
    }
 
    static int countAnagrams(String text, String word)
    {
        int N = text.length();
        int n = word.length();
 
        // Initialize result
        int res = 0;
 
        for (int i = 0; i <= N - n; i++) {
 
            String s = text.substring(i, i + n);
 
            // Check if the word and substring are
            // anagram of each other.
            if (araAnagram(word, s))
                res++;
        }
     
        return res;
    }
 
    // Driver code
    public static void main(String args[])
    {
        String text = "forxxorfxdofr";
        String word = "for";
        System.out.print(countAnagrams(text, word));
    }
}
Output: 
3

 

An Efficient Solution is to use count array to check for anagrams, we can construct current count window from previous window in O(1) time using sliding window concept. 



Java




// An efficient Java program to count anagrams of a
// pattern in a text.
import java.io.*;
import java.util.*;
 
class Solution {
    public static int countAnagrams(String s, String p)
    {
        // change CHARACTERS to support range of supported
        // characters
        int CHARACTERS = 256;
        int sn = s.length();
        int pn = p.length();
        int count = 0;
        if (sn < 0 || pn < 0 || sn < pn)
            return 0;
 
        char[] pArr = new char[CHARACTERS];
        char[] sArr = new char[CHARACTERS];
        int i = 0;
        // till window size
        for (; i < pn; i++) {
            sArr[CHARACTERS - s.charAt(i)]++;
            pArr[CHARACTERS - p.charAt(i)]++;
        }
        if (Arrays.equals(pArr, sArr))
            count += 1;
        // next window
        for (; i < sn; i++) {
            sArr[CHARACTERS - s.charAt(i)]++;
            sArr[CHARACTERS - s.charAt(i - pn)]--;
 
            if (Arrays.equals(pArr, sArr))
                count += 1;
        }
        return count;
    }
    // Driver code
    public static void main(String args[])
    {
        String text = "forxxorfxdofr";
        String word = "for";
        System.out.print(countAnagrams(text, word));
    }
}

C++




#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    static int findAnagrams(const std::string& text,
                            const std::string& word)
    {
        int text_length = text.length();
        int word_length = word.length();
        if (text_length < 0 || word_length < 0
            || text_length < word_length)
            return 0;
 
        constexpr int CHARACTERS = 256;
        int count = 0;
        int index = 0;
        std::array<char, CHARACTERS> wordArr;
        wordArr.fill(0);
        std::array<char, CHARACTERS> textArr;
        textArr.fill(0);
 
        // till window size
        for (; index < word_length; index++) {
            wordArr[CHARACTERS - word[index]]++;
            textArr[CHARACTERS - text[index]]++;
        }
        if (wordArr == textArr)
            count += 1;
        // next window
        for (; index < text_length; index++) {
            textArr[CHARACTERS - text[index]]++;
            textArr[CHARACTERS
                    - text[index - word_length]]--;
 
            if (wordArr == textArr)
                count += 1;
        }
        return count;
    }
};
 
int main()
{
    const std::string& text = "forxxorfxdofr";
    const std::string& word = "for";
 
    cout << Solution::findAnagrams(text, word);
    return 0;
}
Output: 
3

 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :