Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Count Anagram Occurrences

Sliding Windowmedium

Implement `countAnagrams(s, p)` returning how many start indices in `s` begin a substring that is an anagram of `p`.

Sample tests

Input: countAnagrams("cbaebabacd", "abc")
Output: 2
Input: countAnagrams("abab", "ab")
Output: 3

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Rebuilding the full count each step instead of updating it.

Learning resources

  • MDN: String
Approach & explanation (try first)

Comparing fixed-window character counts to the pattern counts finds anagram starts in O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.