Skip to content

Find All Anagrams in a String

MediumSliding Window
Decode it first. Clues, constraints, pattern and plan before any code.

Given strings s and p, return the start index of every substring of s that is an anagram of p (the same letters with the same counts, in any order). Return the indices in increasing order.

s = "cbaebabacd", p = "abc"   →  [0, 6]   ("cba", "bac")
s = "abab",       p = "ab"    →  [0, 1, 2]
s = "a",          p = "ab"    →  []

Constraints

  • 1 <= s.length, p.length <= 3 * 10^4
  • s and p consist of lowercase English letters.