Count Occurences of Anagrams | Practice | GeeksforGeeks

Given a word pat and a text txt. Return the count of the occurences of anagrams of the word in the text.
Example 1:
Input:
txt = forxxorfxdofr
pat = for
Output: 3
Explanation: for, orf and ofr appears
in the txt, hence answer is 3.

Example 2:
Input:
txt = aabaabaa
pat = aaba
Output: 4
Explanation: aaba is present 4 times
in txt.

Your Task:
Complete the function search() which takes two strings pat, txt, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(26) or O(256)
Constraints:
1 <= |pat| <= |txt| <= 105
Both string contains lowercase english letters.
 
0
abhinavverma281 week ago
 int search(string pat, string txt) {    int K = pat.size();    int N = txt.size();    int start = 0;    int end = 0;    int countOfAnagrams = 0;        vector<int> pattern_hash(26, 0);    vector<int> hash(26, 0);        for (char ch : pat)    ++pattern_hash[ch - 'a'];            while (end < N)    {        ++hash[txt[end] - 'a'];                if (end - start + 1 < K)        ++end;                else if (end - start + 1 == K)        {            if (pattern_hash == hash)            {                ++countOfAnagrams;            }                        if(hash[txt[start] - 'a'] != 0)            --hash[txt[start] - 'a'];                        ++start;            ++end;        }    }
 return countOfAnagrams;    } 
0
abhinavverma28
This comment was deleted.
-1
19bcs13142 weeks ago

Simplest java soln
class Solution {

    int search(String pat, String txt) {
        // code here
        
        Map<Character,Integer>  map=new HashMap<>();
        for(int k=0;k<pat.length();k++){
            map.put(pat.charAt(k),map.getOrDefault(pat.charAt(k),0)+1);
            
        }
        
        int i=0,j=0,count=map.size(),total=0,n=txt.length();
        int k=pat.length();
        
        while(j<n){
            
            char temp=txt.charAt(j);
            if(map.containsKey(temp)){
                map.replace(temp,map.get(temp)-1);
                if(map.get(temp)==0){
                    count--;
                }
            }
            
            if(j-i+1<k){
                j++;
            }else if(j-i+1==k){
                if(count==0){
                    total++;
                }
                char x=txt.charAt(i);
                if(map.containsKey(x)){
                    if(map.get(x)==0) count++;
                    
                    map.replace(x,map.get(x)+1);
                    i++;
                    j++;
                }else{
                    i++;
                    j++;
                }
                
            }
        }
        
        return total;
    }
}
0
ravikant021113 weeks ago
//simplest solution using sliding window technique class Solution {
   int search(String pat, String txt) {       // code here              if(txt.length() < pat.length()){           return 0;       }              int countpat[] = new int[26];       int counttxt[] = new int[26];             for(int i = 0; i < pat.length(); i++){                 countpat[pat.charAt(i)-'a']++;           counttxt[txt.charAt(i)-'a']++;       }              int count = 0;       if(Arrays.equals(countpat, counttxt)){               count++;       }                  for(int i = pat.length(); i < txt.length(); i++){                                 counttxt[txt.charAt(i)-'a']++;           counttxt[txt.charAt(i-pat.length())-'a']--;                      if(Arrays.equals(countpat, counttxt)){               count++;           }                  }              return count;          }}
+3
hiphopsamreen4 weeks ago
// Sliding Window Approach: = Easiest Approach
int search(string pat, string txt)
{
  int K = pat.size();
  int N = txt.size();
  int i = 0;
  int j = 0;
  int countOfAnagrams = 0;
 
  vector<int> pattern_hash(26, 0);
  vector<int> hash(26, 0);
 
  for (char ch : pat)
    ++pattern_hash[ch - 'a'];
 
  while (j < N)
  {
    ++hash[txt[j] - 'a'];
    if (j - i + 1 < K)
    {
      ++j;
    }
    else if (j - i + 1 == K)
    {
      if (pattern_hash == hash)
      {
        ++countOfAnagrams;
      }
      // 'i' will be a char in txt and that char's ascii value is the index of hash
      if(hash[txt[i] - 'a'] != 0)
      --hash[txt[i] - 'a'];
      ++i;
      ++j;
    }
  }
  return countOfAnagrams;
}
// Note: See Constraints of this problem:
// Both string contains lowercase english letters.
    //cout << 'a'-'a' << endl; // 0
    //cout << 'b'-'a' << endl; // 1
    //cout << 'c'-'a' << endl; // 2
0
rishavdey20001 month ago
//Simple Java Solution by Sliding Window Technique
class Solution {   int search(String pat, String txt)    {       // code here       int CP[] = new int[26];       int CT[] = new int[26];              for(int i=0;i<pat.length();i++)       {           CP[pat.charAt(i)-'a']++;           CT[txt.charAt(i)-'a']++;       }              int count = 0;       for(int i=pat.length();i<txt.length();i++)       {           if(isSame(CP,CT))           count++;                      CT[txt.charAt(i)-'a']++;           CT[txt.charAt(i-pat.length())-'a']--;       }              return count;   }      boolean isSame(int CP[], int CT[])   {       for(int i=0;i<26;i++)       {           if(CP[i]!=CT[i])           return false;       }              return true;   }}
0
pavansunny5671 month ago
HINT ---Create hash like list to compare
Python solution
among 26 alphabets the given PAT has some occurances.....fill the occurances in a list like this PAT="for" then list=[0,0,0,0,0,1,........], 1 at f's place and and 1 at ‘o’ and ‘r’ place . this act as comparing hash
Now do similar addition and subtraction in ans list for every k elements, where k represents length of PAT given
if both lists matches add +1 to answer.....hehe anthe
def search(self,pat, txt):
	    # code here
	    k=len(pat)
	    n=len(txt)
	    #Two lists
	    pat_list=[0]*26
	    ans_list=[0]*26
	    if n<k:
	        return 0
        ret=0
        #creating hash list to compare
        #97 is ord(a) so , subtracting from it gives
        #index number
        for ele in pat:
            index=ord(ele.lower())-97
            pat_list[index]+=1
        
        #first k elements
        for i in range(k):
           index=ord(txt[i].lower())-97
           ans_list[index]+=1
         
         #repeating the process for n
        for i in range(k,n):
            #comparing if match occured
            if ans_list==pat_list:
                ret+=1
            remove=ord(txt[i-k].lower())-97
            ans_list[remove]-=1
            index=ord(txt[i].lower())-97
            ans_list[index]+=1
        
        if ans_list==pat_list:
            ret+=1
            
        return ret
+1
archit232001 month ago
JAVA Simple and Easy to Understand approach:
int search(String s2, String s1) {
        char []c=s2.toCharArray();
        char[] c1=s1.toCharArray();
        Map<Character,Integer> m=new LinkedHashMap<>();
        Map<Character,Integer> m1=new LinkedHashMap<>();
        for(int j=0;j<s2.length();j++){
            m.put(c[j],(m.get(c[j])==null?1:m.get(c[j])+1));
        }
        int i=0;
        int j=0;
        int finalAns=0;
        int k=s2.length();
        while(j<s1.length()){
            m1.put(c1[j],m1.get(c1[j])==null?1:(m1.get(c1[j])+1));
            if(j-i+1<k){
                j++;
            }
            else if(j-i+1==k){
                if(m1.equals(m)) {
                    finalAns++;
                }
                m1.put(c1[i],(m1.get(c1[i])-1));
                if(m1.get(c1[i])==0){
                    m1.remove(c1[i]);
                }
                i++;
                j++;
            }
        }
        return finalAns;
    }
0
sourabhgharad19062 months ago
int search(String pat, String txt) {       HashMap<Character,Integer> pmap = new HashMap<>();       HashMap<Character,Integer> tmap = new HashMap<>();       int j = 0;       int k;       int count = 0;       for(int i=0;i<pat.length();i++){           char ch = pat.charAt(i);           pmap.put(ch,pmap.getOrDefault(ch,0)+1);       }       for(k=0;k<pat.length();k++){           char ch = txt.charAt(k);           tmap.put(ch,tmap.getOrDefault(ch,0)+1);       }       if(pmap.equals(tmap)){           count++;       }       while(j<txt.length()-pat.length() && k<txt.length()){           char ch = txt.charAt(j);           char c = txt.charAt(k);           if(tmap.get(ch) == 1){               tmap.remove(ch);           }           else{               tmap.put(ch,tmap.get(ch)-1);           }           tmap.put(c,tmap.getOrDefault(c,0)+1);           if(pmap.equals(tmap)){               count++;           }           j++;           k++;       }       return count;   }
0
shalini15052 months ago
*USING SLIDING WINDOW*
int search(string pat, string txt) {    int i=0,j=0;    vector<int>ans(26,0);    for(int c=0;c<pat.size();c++)    {        ans[pat[c]-'a']++;    }    int sum=0;    vector<int>arr(26,0);    while(j<txt.size())    {        while((j-i)<pat.size())        {            arr[txt[j]-'a']++;            j++;        }        if(ans==arr)        {            sum++;        }        arr[txt[i]-'a']--;        i++;    }    return sum;} 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.