Problem 248517 · medium · Phase 02 Linear Data Structures

Count Anagram Windows

strings · anagrams · sliding window

Write count_anagram_windows(s, p) that returns how many substrings of s are anagrams of p (same characters with the same multiplicities, in any order). Substrings at different positions count separately even if they are equal. Comparison is case-sensitive.

Examples

Input:  s = "cbaebabacd", p = "abc"
Output: 2
Explanation: "cba" at index 0 and "bac" at index 6.

Input:  s = "abab", p = "ab"
Output: 3

Input:  s = "aaaa", p = "aa"
Output: 3

Constraints

  • 0 <= len(s) <= 10**5, 1 <= len(p) <= 10**4, printable ASCII
  • Target: O(len(s)) time; checking every window with sorting is too slow

Goals

  • Maintain character counts for a window of fixed width
  • Update counts incrementally as the window slides
  • Compare two count tables efficiently
Starting Python…