Skip to content

Commit 08ad12d

Browse files
Added day16 solution
1 parent 20401ef commit 08ad12d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
vector<int> findAnagrams(string s, string p) {
4+
5+
if(s.size() == 0 || p.size() > s.size()) return {};
6+
vector<int> curr_window(26, 0), pattern(26, 0), anagrams_start;
7+
8+
for(auto c : p)
9+
pattern[c - 'a']++;
10+
11+
/*
12+
1) eliminate least recently used characters
13+
2) length of sliding window should always be <= length of pattern to match. If it exceeds, we have to make the sliding window length = pattern length. For this purpose we use 1)
14+
*/
15+
16+
/*
17+
At i = 3, we eliminate char at i = 0 from s to make our sliding window have characters at s[1],s[2],s[3]
18+
At i = 4, we eliminate char at i = 1 from s to make our sliding window have characters at s[2],s[3],s[4]
19+
and so on..
20+
*/
21+
22+
for(auto i=0; i<s.size(); i++){
23+
curr_window[s[i] - 'a']++; //include current unseen character
24+
25+
if(i >= p.size()){ //exclude least recently used characters
26+
auto exclude = s[i - p.size()];
27+
curr_window[exclude - 'a']--;
28+
}
29+
30+
if(curr_window == pattern){ //found anagram, store its start index
31+
anagrams_start.push_back(i - p.size() + 1); //+1 for 0 based indexing
32+
}
33+
}
34+
return anagrams_start;
35+
}
36+
};

0 commit comments

Comments
 (0)