Determine whether a string contains a contiguous rearrangement of all characters in a given pattern.
Problem
Input. Two Python strings, pattern and text.
Output. Return True if any substring of text is a permutation of pattern; otherwise return False.
Rules. A matching substring must be contiguous and contain exactly the pattern’s character counts.
Use exact code points, including case and whitespace. Do not modify either string.
A longer pattern returns False. An empty pattern returns True, including with empty text.
Example. Pattern "ab" and text "eidbaooo" return True because "ba" starts at index 3.
The same pattern with "eidboaoo" returns False; separated letters do not form a substring.
Picture: Keep Exactly the Pattern’s Width
Problem trace
Separate aab/abb counts: matching types do not match multiplicity
Reference drawing
Problem trace
Equal character counts qualify only at the required window length
Execution trace
- key need
- a:1, b:1
- key window
- e:1, i:1
- L
- 0
- key window
- e:1, i:1→d:1, i:1
- L
- 0→1
- R
- 1→2
- key window
- d:1, i:1→b:1, d:1
- L
- 1→2
- R
- 2→3
- key window
- b:1, d:1→a:1, b:1
- L
- 2→3
- R
- 3→4
- Recognize it
- Use it when a contiguous match may appear in any order: equal multisets require equal length, so only windows whose width equals the pattern length can qualify.
- Keep true
- Before each comparison, window contains exactly text[R - pattern_length + 1..R], because the new right character was added and the one character that fell off the left was removed.
- Reuse it
- When every candidate has a known width, maintain its summary by adding the entering item and removing the outgoing item; compare summaries instead of rebuilding or enumerating arrangements.
| Window | Add/remove to reach it | Compare with {a:1, b:1} |
|---|---|---|
ei | Initialize width 2 | Different |
id | Add d, remove e | Different |
db | Add b, remove i | Different |
ba | Add a, remove d | Equal: return True |
Before every comparison, window counts exactly the current width-sized substring.
Add text[right], subtract text[right-width], then delete a zero entry before comparing.
The figure’s L is right-width+1; R is right after the slide.
Deletion keeps state sparse without relying on zero-entry equality rules.
Exact multiset equality explains why equal counts suffice; fixed width selects the candidate intervals.
Code
from collections import Counter
def check_inclusion(pattern: str, text: str) -> bool:
if len(pattern) > len(text):
return False
need = Counter(pattern)
window = Counter(text[: len(pattern)])
if window == need:
return True
for right in range(len(pattern), len(text)):
window[text[right]] += 1
left_char = text[right - len(pattern)]
window[left_char] -= 1
if window[left_char] == 0:
del window[left_char]
if window == need:
return True
return False
For pattern length , text length , and tested windows, expected cost is . Here bounds counter keys inspected per equality. A fixed alphabet gives time; auxiliary space is .
Change 1: Return Every Matching Start
New task. Report all matches, including overlaps. An empty pattern matches all boundaries.
Picture and change. Continue after equality and save each start.
Code.
from collections import Counter
def anagram_starts(pattern, text):
width = len(pattern)
if width > len(text):
return []
need, window = Counter(pattern), Counter(text[:width])
answer = [0] if window == need else []
for right in range(width, len(text)):
window[text[right]] += 1
outgoing = text[right - width]
window[outgoing] -= 1
if window[outgoing] == 0:
del window[outgoing]
if window == need:
answer.append(right - width + 1)
return answer
Check. ("ab", "abab") gives [0, 1, 2]; ("", "ab") also gives [0, 1, 2].
Use when. Every position is needed. Output storage can be .
Change 2: Return the First Start
New task. Return a location, with -1 for no match.
Picture and change. Reuse the complete function above; this simple wrapper still enumerates all matches.
Code. Place after anagram_starts:
def first_anagram_start(pattern, text):
starts = anagram_starts(pattern, text)
return starts[0] if starts else -1
Check. ("ab", "eidbaooo") gives 3; ("ab", "eeee") gives -1; empty pattern gives 0.
Use when. A location is required. This wrapper does not inherit the Boolean reference’s early-stop or constant-output-space behavior.
Failure: Comparing Before Removal
The summary temporarily has width plus one after insertion. Comparing then tests the wrong interval.
Transfer Check
What changes if the pattern repeats a character?
Reasoned Answer
Width and add/remove mechanics stay unchanged. Exact multiplicities enforce repetitions; character membership alone cannot.
Why Fixed Width Is Enough
Equal multiplicities imply equal total length, so no other substring widths can match. This differs from windows that repeatedly shrink to repair a variable validity condition. Each step here removes exactly the character that falls outside the next fixed-width interval.
With zero width, the all-starts variant adds and removes the same character before each comparison.
Its counter stays empty, producing every boundary from 0 through len(text).
The original Boolean reference returns immediately at its initial empty-window equality.
To avoid enumerating all matches for a first-index request, return the current start directly at the first equality. That implementation would need its own early-stop tests; the displayed wrapper intentionally prioritizes reuse over that optimization. Counter equality can inspect multiple keys, so do not call each comparison constant-time for an unbounded alphabet.