← Home

438. Find All Anagrams in a String

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
sliding windowC++Markdown
438

The trick here is to name the state correctly, then let the implementation follow. For 438. Find All Anagrams in a String, the solution in this repository is mainly a sliding window solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: sliding window, greedy.

The notes already sitting in the source point us in the right direction:

  • TLE

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findAnagrams.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02class Solution {
03public:
04    vector<int> findAnagrams(string s, string p) {
05        if(p.size() > s.size()) return vector<int>();
06        vector<int> ans;
07        
08        sort(p.begin(), p.end());
09        
10        for(int i = 0; i < s.size() - (p.size()-1); i++){
11            string s1 = s.substr(i, p.size());
12            sort(s1.begin(), s1.end());
13            if(s1 == p) ans.push_back(i);
14        }
15        
16        return ans;
17    }
18};
19
20//https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/92007/Sliding-Window-algorithm-template-to-solve-all-the-Leetcode-substring-search-problem.
21//sort by votes, dico's answer(7 votes)
22//Runtime: 52 ms, faster than 31.03% of C++ online submissions for Find All Anagrams in a String.
23//Memory Usage: 10.3 MB, less than 96.82% of C++ online submissions for Find All Anagrams in a String.
24class Solution {
25public:
26    vector<int> findAnagrams(string s, string p) {
27        vector<int> ans;
28        map<char, int> pcount;
29        for(char c: p){
30            if(pcount.find(c) == pcount.end()){
31                pcount[c] = 1;
32            }else{
33                pcount[c]++;
34            }
35        }
36        
37        map<char, int> wcount; //the occurence of chars in a sliding window
38        int start = 0, end = 0, match = 0;
39        
40        while(end < s.size()){
41            char c1 = s[end];
42            if(pcount.find(c1) != pcount.end()){
43                //update wcount
44                if(wcount.find(c1) == wcount.end()){
45                    wcount[c1] = 1;
46                }else{
47                    wcount[c1]++;
48                }
49                //increase 'match' when the occurences match each other
50                if(pcount[c1] == wcount[c1])match++;
51            }
52            
53            //find start while 'match' is the correct number
54            while(match == pcount.size()){
55                //only when the matched kind of char's count are right,
56                // and the total matched count are right,
57                // we find an valid start
58                if(end - start + 1 == p.size()){
59                    ans.push_back(start);
60                }
61                
62                //discard s[start], update sliding window and 'match'
63                char c2 = s[start];
64                if(pcount.find(c2) != pcount.end()){
65                    wcount[c2]--;
66                    if(wcount[c2] < pcount[c2])match--;
67                }
68                start++;
69            }
70        
71            end++;
72        }
73        
74        return ans;
75    }
76};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.