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 spsps
Example 1
Output: [0, 6]
Explanation: "cba" at 0 and "bac" at 6 are anagrams of "abc".
Example 2
Output: [0, 1, 2]
Explanation: "ab" at 0, "ba" at 1 and "ab" at 2.
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, ps
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].
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 pspsp
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 needp
So each slot of needppp
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, missingppmissingmissing
When missingpp
Sliding the window by one letter
Which letter leaves at each step? Let ii - niii - n + 1
Java Solution
The method findAnagrams
- First, create the empty list
and letresult be the length ofn . Ifp is longer thanp , returns right away, because no window ofresult is that long.s - Fill the 26-slot array
with the letter counts ofneed . Subtractingp from a letter gives its slot: 0 for a, 1 for b, and so on. Set'a' tomissing .n - Move
overi with one loop. The letter ats enters: the testi compares its slot with 0 and then lowers it, soneed[...]-- > 0 drops only when the slot was above 0 before.missing - Once
is at leasti , the letter atn leaves:i - n raises its slot first, and if the slot is now above 0,++need[...] grows.missing - If
is 0, add the window's start,missing , toi - n + 1 . After the loop, returnresult .result
The mainpps
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:
[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 pmissingmissing
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 >= ni > ns
The original implementation,
Complexity
The work is one pass over pneeds
- Time: O(m + n), where m is the length of
and n the length ofs . Fillingp reads the n letters ofneed once, and each of the m letters ofp enters the window once and leaves at most once, each a single slot update.s - Space: O(1) besides the result.
always has 26 slots andneed is one number, however long the strings are.missing
To answer only whether some anagram of one string appears in another, stopping at the first match, see