Return how many substrings of s are anagrams of part. Each starting position
counts separately. Assume lowercase letters only.
countSubstringAnagrams(s, part)
Input format: s | part.
s="cbaebabacd", part="abc" // → 2
s="abab", part="ab" // → 3 ("ab", "ba", "ab")
s="aa", part="aaa" // → 0
This is the counting version of "does s contain an anagram of part": instead of stopping at the first match, tally every starting position whose window is a rearrangement of part. The underlying comparison is identical to the yes/no version — only difference is you keep scanning and count every match.
Building a fresh frequency table for each of the roughly n windows costs O(k) per table (k = len(part)), O(n·k) overall. But adjacent windows overlap in all but one character. Rebuilding from scratch on every slide ignores that overlap.
Maintain one running frequency table for the current window:
Every successful comparison is an anagram — increment your count. Checking every window (rather than stopping early) naturally handles overlapping matches, since the problem counts each valid starting position separately.
Each slide does constant work — one increment, one decrement, one fixed-size comparison — so scanning the whole string costs O(n), versus O(n·k) brute force. Space stays O(1), bounded by the alphabet size.
When a problem asks you to evaluate the same property across every fixed-size window, and windows overlap heavily, don't recompute from scratch — maintain a running summary and update it incrementally. Whether you stop at the first hit or count every hit is a small change on the same core technique.
def count_substring_anagrams(s, part):
if len(part) > len(s):
return 0
need = [0] * 26
win = [0] * 26
for ch in part:
need[ord(ch) - 97] += 1
count = 0
for i in range(len(s)):
win[ord(s[i]) - 97] += 1
if i >= len(part):
win[ord(s[i - len(part)]) - 97] -= 1
if i >= len(part) - 1 and win == need:
count += 1
return count
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.