Find all Anagrams in a String


Find All Anagrams in a String – LeetCode #438


Problem Statement

You are given two strings s and p.

Your task is to return a list of all the start indices in s where the substring is an anagram of p.

You can return the result in any order.


Examples


Constraints


Intuition

We need to identify all substrings in s of length equal to p.length() that are anagrams of p.

This can be seen as a fixed-size sliding window + frequency map comparison problem:


Approach

  1. Create a frequency array counter of size 26 and initialize it with character frequencies from p.

  2. Use two pointers i and j to define the sliding window of length k = p.length() over string s.

  3. For every character entering the window (s[j]), decrement its count from counter.

  4. When window size reaches k:

    • Check if all values in counter are 0 (indicating an anagram).

    • If yes, add i (start index of window) to result list.

    • Before moving i forward, restore the character going out (s[i]) by incrementing its count in counter.

  5. Move the window forward and repeat.


Java Code

class Solution {
    private boolean allZero(int[] counter) {
        for (int num : counter) {
            if (num != 0) return false;
        }
        return true;
    }

    public List<Integer> findAnagrams(String s, String p) {
        int n = s.length();
        int k = p.length();
        List<Integer> result = new ArrayList<>();
        if (n < k) return result;

        int[] counter = new int[26];

        // Step 1: Count frequencies of characters in p
        for (char ch : p.toCharArray()) {
            counter[ch - 'a']++;
        }

        // Step 2: Sliding window over s
        int i = 0, j = 0;
        while (j < n) {
            counter[s.charAt(j) - 'a']--;

            if (j - i + 1 == k) {
                if (allZero(counter)) {
                    result.add(i);
                }

                // Slide the window
                counter[s.charAt(i) - 'a']++;
                i++;
            }

            j++;
        }

        return result;
    }
}

Time and Space Complexity


Dry Run

Input:

s = "cbaebabacd", p = "abc"

Step-by-step:

Output: [0, 6]


Conclusion

This problem is a textbook example of the Fixed-Size Sliding Window + Hash Table Lookup pattern:

This approach generalizes well to: