educative.io

Educative

Anagram Solution as Per Course Pattern - LC Pass

//https://github.com/rsghotra/Patterns/blob/master/SlidingWindow/main.cpp
    vector<int> findAnagrams(string str, string pattern) {`
        unordered_map<char, int> frequencies;
        for(char ch: pattern) {
            frequencies[ch]++;
        }
        
        int windowStart = 0;
        int matchCount = 0;
        vector<int> result;
        
        for(int windowEnd = 0; windowEnd < str.size(); windowEnd++) {
            if(frequencies.find(str[windowEnd]) != frequencies.end()) {
                frequencies[str[windowEnd]]--;
                if(frequencies[str[windowEnd]] == 0) {
                    matchCount++;
                }
            }
            if(matchCount == frequencies.size()) {
                result.push_back(windowStart);
            }
            if(windowEnd - windowStart + 1 == pattern.length()) {
                if(frequencies.find(str[windowStart]) != frequencies.end()) {
                    if(frequencies[str[windowStart]] == 0) {
                        matchCount--;
                    }
                    //put the char back on map
                    frequencies[str[windowStart]]++;
                }
                windowStart++;
            }
        }
        return result;
    }

Hi @Rupinder_Ghotra

Your solution is fine and we appreciate it.

Happy learning,