Skip to content
mlmentorship

Permutation in String

Check whether any substring has the same letter counts as the pattern.

Published · 12 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Permutation in String

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Slide one width-2 window over "eidbaooo"; add R, remove the outgoing L character, then compare counts.

Problem trace

Equal character counts qualify only at the required window length

Input and goalCheck whether any substring has the same letter counts as the pattern.
Count the first width-2 windowPattern ab needs one a and one b. Initial window ei has different counts.
Le0Ri1d2b3a4o5o6o7
range[0..1] = "ei"comparisone:1,i:1 != a:1,b:1
saved stateneeda:1, b:1windowe:1, i:1
key need
a:1, b:1
key window
e:1, i:1
L
0

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.
Pattern ab needs one a and one b. Initial window ei has different counts. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does ba qualify regardless of order? Why does a longer window with these letters fail this test?
Full interview answer 12 min read
Reading depth

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

Worked example: character multiplicities must match, not only membershipPatterns aab and window abb share the same character set. Their counts differ, so the window is not a permutation.Keep every character copy in itsshared character binReference: aabaaacount 2bbcount 1Compare: abbaa-count 1bbbcount 2The missing a and extra b defeatexact count equality.
Read it this way: Patterns aab and window abb share the same character set. Their counts differ, so the window is not a permutation. Does sharing the set of letters a and b make abb a permutation of aab?
Reference drawing

Problem trace

Equal character counts qualify only at the required window length

Worked example: character multiplicities must match, not only membershipPatterns aab and window abb share the same character set. Their counts differ, so the window is not a permutation.Keep every character copy in itsshared character binReference: aabaaacount 2bbcount 1Compare: abbaa-count 1bbbcount 2The missing a and extra b defeatexact count equality.
Execution trace
Input and goalCheck whether any substring has the same letter counts as the pattern.
Count the first width-2 windowPattern ab needs one a and one b. Initial window ei has different counts.
Le0Ri1d2b3a4o5o6o7
range[0..1] = "ei"comparisone:1,i:1 != a:1,b:1
saved stateneeda:1, b:1windowe:1, i:1
key need
a:1, b:1
key window
e:1, i:1
L
0

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.
Pattern ab needs one a and one b. Initial window ei has different counts. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does ba qualify regardless of order? Why does a longer window with these letters fail this test?
Read it this way: Patterns aab and window abb share the same character set. Their counts differ, so the window is not a permutation. Does sharing the set of letters a and b make abb a permutation of aab?
WindowAdd/remove to reach itCompare with {a:1, b:1}
eiInitialize width 2Different
idAdd d, remove eDifferent
dbAdd b, remove iDifferent
baAdd a, remove dEqual: 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.