Find all anagrams of a string in another string?
public List<int> FindAnagrams(string s, string p) {
List<int> result = new List<int>();
if (p.Length > s.Length) return result;
int[] pCount = new int[26];
int[] sCount = new int[26];
Follow on:
for (int i = 0; i < p.Length; i++) {
pCount[p[i] - 'a']++;
sCount[s[i] - 'a']++;
if (Enumerable.SequenceEqual(pCount, sCount))
result.Add(0);
for (int i = p.Length; i < s.Length; i++) {
sCount[s[i] - 'a']++;
sCount[s[i - p.Length] - 'a']--;
if (Enumerable.SequenceEqual(pCount, sCount))
result.Add(i - p.Length + 1);
return result;
Explanation:
Sliding window with frequency count arrays for the pattern and current window.