438. Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
// Brute Force
vector<int> findAnagrams(string s, string p) { // time: O(s_len * n_len); space: O(s_len)
    vector<int> res, record(128, 0);
    int s_len = s.size(), p_len = p.size(), i = 0;
    for (const char& ch : p) ++record[ch];
    while (i < s_len) {
        bool success = true;
        vector<int> tmp = record;
        for (int j = i; j < i + p_len; ++j) {
            if (--tmp[s[j]] < 0) {
                success = false;
                break;
            }
        }
        if (success) {
            res.push_back(i); 
        }
        ++i;
    }
    return res;
}
// Optimized Brute Force
vector<int> findAnagrams(string s, string p) { // time: O(s_len); space: O(s_len)
    vector<int> res, cnt1(128, 0), cnt2(128, 0);
    int s_len = s.length(), p_len = p.length();
    for (int i = 0; i < p_len; ++i) {
        ++cnt1[s[i]];
        ++cnt2[p[i]];
    }
    if (cnt1 == cnt2) res.emplace_back(0);
    for (int i = p_len; i < s_len; ++i) {
        ++cnt1[s[i]];
        --cnt1[s[i - p_len]];
        if (cnt1 == cnt2) res.emplace_back(i - p_len + 1);
    }
    return res;
}
// Sliding Window
vector<int> findAnagrams(string s, string p) { // time: O(s_len + p_len); space: O(s_len)
    vector<int> res, record(128, 0);
    for (const char& ch : p) ++record[ch];
    int begin = 0, end = 0, counter = p.length(), s_len = s.length(), p_len = p.length();
    while (end < s_len) {
        if (record[s[end++]]-- >= 1) --counter;
        if (counter == 0) res.emplace_back(begin);
        if (end - begin == p_len && record[s[begin++]]++ >= 0) ++counter;
    }
    return res;
}

Last updated

Was this helpful?