Find All Anagrams in a String

Return the start index of every stretch of s that uses exactly the letters of p, in any order.

Two words are anagrams when one uses the letters of the other in a different order, such as "listen" and "silent". Given two strings s and p of lowercase English letters, return the start index of every substring of s that is an anagram of p. A substring is a run of letters that sit next to each other in s. The indexes can come in any order.

Example 1
Input: s = "cbaebabacd", p = "abc"
Output: [0, 6]
Explanation: "cba" at 0 and "bac" at 6 are anagrams of "abc".
Example 2
Input: s = "abab", p = "ab"
Output: [0, 1, 2]
Explanation: "ab" at 0, "ba" at 1 and "ab" at 2.
Solution

The Idea

"Listen" and "silent" use the same six letters, once each, just in a different order. So to test whether two words are anagrams, the order does not matter at all. You only count how many times each letter appears in each word, and compare the counts.

In Example 1, p is "abc", so an anagram of it is one a, one b and one c in any order. It is also exactly 3 letters long, so the only places to look in s = "cbaebabacd" are its runs of 3 letters next to each other. Call such a run a window. There are eight of them, starting at indexes 0 to 7.

Look at the picture below. The orange bracket labelled "start 0" covers c, b, a: one of each letter, so it is a match. The orange bracket labelled "start 6" covers b, a, c, the second match. Together they give the answer [0, 6].

The string cbaebabacd with indexes 0 to 9. The window at start 0 holds c, b, a and the window at start 6 holds b, a, c: both are matches for abc. Sliding from start 0 to start 1, c leaves and e enters, so the window b, a, e is not a match.

Now look at the teal bracket labelled "start 1". It is the window at start 0 moved one place to the right: c left on the left side and e entered on the right side, while b and a stayed. That raises a question. Why count b and a again for every window, when only two letters changed?

There is no need to. When the window moves one place, exactly one letter leaves and one letter enters, so the counts can be updated in two small steps instead of being counted again. A window of fixed length that moves along a string one place at a time like this is called a sliding window.

Solution Approach

Turning that idea into code starts with why counting every window from scratch is slow. Then it settles three things: what to count, how to tell that a window is a match, and which letter leaves when the window slides.

Counting every window from scratch

What does the simple way cost? For every start index, count the letters of the window and compare them with the counts of p. With m letters in s and n in p, that is about m windows of n letters each. For a 10,000-letter s and a 1,000-letter p, it reads about 9 million letters, nearly all of them read before.

Counting what the window still needs

Which counts should we keep? One array of 26 numbers is enough, one slot per letter from a to z, called need. It starts as the letter counts of p, so for "abc" the slots for a, b and c hold 1 and the rest hold 0. A letter entering the window lowers its slot by one, and a letter leaving raises it by one.

So each slot of need holds the count of that letter in p minus its count in the window. A slot above 0 means the window still lacks that letter. A slot below 0 means the window has more of it than p, as the window "aaa" in "aaab" has when p is "aab".

Telling when the window is a match

How do we know a window is an anagram without checking all 26 slots? Keep one more number, missing: how many letters of p the window does not cover yet. It starts at n. When a letter enters and its slot was above 0 before, p needed it, so missing drops by one. When a letter leaves and its slot is above 0 afterwards, the window lost a needed letter, so missing grows by one.

When missing is 0, the window covers every letter of p. A full window has exactly n letters, as many as p, so there is no room left for an extra one: the window is an anagram.

Sliding the window by one letter

Which letter leaves at each step? Let i be the index of the letter that enters. Once the window is full, the letter n places back, at i - n, leaves. While i is below n, the window is still filling up and nothing leaves. A window that ends at i starts at i - n + 1, and that is the index to record on a match.

Java Solution

The method findAnagrams works in these steps:

  1. First, create the empty list result and let n be the length of p. If p is longer than s, return result right away, because no window of s is that long.
  2. Fill the 26-slot array need with the letter counts of p. Subtracting 'a' from a letter gives its slot: 0 for a, 1 for b, and so on. Set missing to n.
  3. Move i over s with one loop. The letter at i enters: the test need[...]-- > 0 compares its slot with 0 and then lowers it, so missing drops only when the slot was above 0 before.
  4. Once i is at least n, the letter at i - n leaves: ++need[...] raises its slot first, and if the slot is now above 0, missing grows.
  5. If missing is 0, add the window's start, i - n + 1, to result. After the loop, return result.

The main method runs both examples, a p with a repeated letter, a string of one repeated letter where matches overlap, and a p longer than s.

Java
import java.util.ArrayList;
import java.util.List;

public class FindAllAnagramsInAString {

    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int n = p.length();
        if (n > s.length()) {
            return result;
        }
        int[] need = new int[26];             // letters of p minus letters in the window
        for (int k = 0; k < n; k++) {
            need[p.charAt(k) - 'a']++;
        }
        int missing = n;                      // letters of p not yet matched by the window
        for (int i = 0; i < s.length(); i++) {
            if (need[s.charAt(i) - 'a']-- > 0) {
                missing--;                    // the entering letter was needed
            }
            if (i >= n && ++need[s.charAt(i - n) - 'a'] > 0) {
                missing++;                    // the leaving letter was a needed one
            }
            if (missing == 0) {
                result.add(i - n + 1);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(findAnagrams("cbaebabacd", "abc"));
        System.out.println(findAnagrams("abab", "ab"));
        System.out.println(findAnagrams("aaab", "aab"));
        System.out.println(findAnagrams("aaaaa", "aa"));
        System.out.println(findAnagrams("a", "ab"));
    }
}

Running it prints:

Output
[0, 6]
[0, 1, 2]
[1]
[0, 1, 2, 3]
[]

The first line, [0, 6], is the answer to Example 1. In the second, [0, 1, 2], the matches overlap: "ab" at 0 and "ba" at 1 share the b at index 1.

Look at the third line, [1], from "aaab" with p = "aab". The window at 0 is "aaa": the third a takes the slot for a down to -1, and missing stays at 1 because no b has entered. The window at 1 is "aab", the b brings missing to 0, and 1 is recorded.

The fourth line shows that every 2-letter window of "aaaaa" is a match, so the four windows at 0 to 3 are all listed even though they overlap. The last line is empty because "ab" is longer than "a".

The leaving test must be i >= n. With i > n, the first letter of s never leaves, so every later window holds one letter too many. Run with that change, the first example prints [0, 1, 2, 3, 4, 5, 6] instead of [0, 6].

The original implementation, FindAllAnagrams.java, is on GitHub.

Complexity

The work is one pass over p to fill need, then one pass over s with a fixed amount of work per letter.

  • Time: O(m + n), where m is the length of s and n the length of p. Filling need reads the n letters of p once, and each of the m letters of s enters the window once and leaves at most once, each a single slot update.
  • Space: O(1) besides the result. need always has 26 slots and missing is one number, however long the strings are.

To answer only whether some anagram of one string appears in another, stopping at the first match, see Permutation in String.