C++ O(N) Time O(1) Space, 32ms Beats 91%, Sliding Window + Counting


  • 0
    M

    I use vector cnts for counting number of characters. First cnts is filled with counts of p characters. Then I traverse through s 1 char at a time using sliding window, decreasing counts of chars, if all counts are zero it means that current sliding window in s is anagram for p. Complexity: O(N) Time, O(1) Space.

    class Solution {
    public:
        vector<int> findAnagrams(string const & s, string const & p) {
            vector<int> result, cnts(128);
            int nzcnt = 0, cc = 0;
            for (char c: p) if (++cnts[c] == 1) ++nzcnt;
            for (int i = 0; i < s.size(); ++i) {
                cc = --cnts[s[i]];
                nzcnt += cc == -1 ? +1 : cc == 0 ? -1 : 0;
                if (i >= p.size()) {
                    cc = ++cnts[s[i - p.size()]];
                    nzcnt += cc == 1 ? +1 : cc == 0 ? -1 : 0;
                }
                if (i + 1 >= p.size() && nzcnt == 0) result.push_back(i + 1 - p.size());
            }
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.