Find all Anagrams in a string - Leet code

I tried this problem. Both test cases given are getting passed. but when submitting getting runtime error. Can u please identify the error in my code only.

ide->https://ide.codingblocks.com/s/229105

ques->https://leetcode.com/problems/find-all-anagrams-in-a-string/submissions/

would u like to elaborate upon your approach?

first i am making a map of p string . Then i is moving forward and making a substr of length equal to string p length. Then i am iterating over the substr and if the character exists in the map , it is decrementing.
if the elements in the map are zero i am incrementing the count and if count is equal to string p length, the index is being added in the vector.

if( s.size() < p.size()) return ans; this is a condition that needs to be added to remove Runtime errror
but then u get a tle for the code

can you please give other approach then

My idea to solve the problem is that make 2 vector for length of string add the inital freq

  vector<int> findAnagrams(string s, string p) {
        vector<int> ans;
        vector<int> counts(26,0), countp(26,0);
        if(s.size() < p.size())return ans;
        for(int i = 0 ; i < p.size() ; i++){
            counts[s[i]-'a']+=1;
            countp[p[i]-'a']+=1;
        }
        int m = p.size() , n = s.size();
        for(int i  = p.size() ; i < s.size() ; i++){
            if(counts == countp){
                ans.push_back(i-m);
            }
            counts[s[i]-'a']+=1;
            counts[s[i-m]-'a']--;
            
        }
        if(counts == countp)
            ans.push_back(n-m);
        return ans;
    }

now do it like sliding window approach
start from size of pattern string
compare the comp_s with comp_p
if equal add pos i-size of ans vector.
then increment freq of the right pointer character simultaneously decrementing freq of the leftmost
character i-p.size()

you`ll make out a lot from this code.

in case of further doubt ping me

1 Like