AlgoMaster Logo

Find All Anagrams in a String

s=cbaebabacd,p=abc
1public List<Integer> findAnagrams(String s, String p) {
2    List<Integer> result = new ArrayList<>();
3    if (s.length() < p.length()) return result;
4
5    // Frequency arrays for s and p
6    int[] pCount = new int[26];
7    int[] sCount = new int[26];
8
9    // Initialize the frequency arrays
10    for (int i = 0; i < p.length(); i++) {
11        pCount[p.charAt(i) - 'a']++;
12        sCount[s.charAt(i) - 'a']++;
13    }
14
15    // Sliding window over s
16    for (int i = 0; i <= s.length() - p.length(); i++) {
17        // Check if the current window is an anagram
18        if (areArraysEqual(pCount, sCount)) result.add(i);
19
20        // Slide the window
21        if (i + p.length() < s.length()) {
22            sCount[s.charAt(i) - 'a']--; // Remove old char from the count
23            sCount[s.charAt(i + p.length()) - 'a']++; // Add new char to the count
24        }
25    }
26
27    return result;
28}
29
30private boolean areArraysEqual(int[] arr1, int[] arr2) {
31    for (int i = 0; i < arr1.length; i++) {
32        if (arr1[i] != arr2[i]) return false;
33    }
34    return true;
35}
0 / 18
p:abcs:cbaebabacdpCount = {}sCount = {}result = []