You are given two strings of lower-case letters, s and p. An anagram of p is any string that uses exactly the same letters as p, the same number of times each, in any order.
Return every index i where the piece of s that starts at i and has the length of p is an anagram of p. The indices may be returned in any order.
Example 1
Input: s = "nabxbanq", p = "abn" Output: [0, 4] Why: "nab" at 0 and "ban" at 4 use the letters a, b, n
2 more examples and the constraints
Example 2
Input: s = "aaab", p = "aa" Output: [0, 1] Why: matches may overlap; "ab" at 2 is not one
Example 3
Input: s = "ab", p = "abc" Output: [] Why: p is longer than s, so no piece fits
Constraints
- 1 ≤ length of s, length of p ≤ 30,000
- s and p hold only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort every windowO(n·m log m)
- Sliding window of countsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for s and p of 15,000 letters each | Verdict |
|---|---|---|---|
| Sort every window | O(n·m log m) | Mention it, then move on | |
| Sliding window of counts | O(n) | Best; two counts per step |
n = length of s, m = length of p.
Edge cases to test
- p longer than s. "ab" with p = "abc" has no window at all: return [].
- Overlapping matches. "aaab" with p = "aa" matches at 0 and at 1; windows may share letters.
- Repeated letters in p. "aab" needs a twice. Comparing sets of letters instead of counts would accept "abb".
- Match at the very end. "qqqqtop" with p = "pot" matches at 4, the last possible start.
Common mistakes
- Checking the window before it is full, or after removing too early, so the window is one letter short or long.
- Comparing sets of letters rather than counts, which ignores repeats.
- Recording
i(the window's end) instead ofi − m + 1(its start).
How to talk through it
- 1Clarify. Only lower-case letters? Can p be longer than s? Can matches overlap?
- 2Give the brute force. Sort each window and compare with sorted p; say it is O(n·m log m) and why that hurts.
- 3Spot the overlap. Neighbouring windows differ by one letter in and one letter out, so keep counts and update two of them.
- 4Code the window. Add on the right, remove
s[i − m]on the left, then compare 26 counts when the window is full. - 5Test out loud. Run p longer than s, overlapping matches, and a p with a repeated letter.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?