Find All Anagrams in a String

Medium Topics Company Tags

Return the starting indices of every substring of s that is an anagram of p. An anagram contains exactly the same letters with the same counts, possibly in a different order. Matching substrings may overlap. Indices are zero-based, and you may return them in any order.

Example 1:

Input: s = "baca"
p = "ac"

Output: [1,2]

Explanation: The length-2 substrings starting at indices 1 and 2 are "ac" and "ca". Both contain one a and one c, so return [1, 2].

Example 2:

Input: s = "aaaa"
p = "aa"

Output: [0,1,2]

Explanation: The substrings starting at indices 0, 1, and 2 all equal "aa". Overlapping matches are allowed, so all three indices are included.

Example 3:

Input: s = "ab"
p = "abc"

Output: []

Explanation: The pattern has length 3, but s has only two characters. No substring can match, so return an empty array.

Constraints:

  • 1 <= s.length, p.length <= 30000
  • Both strings contain only lowercase English letters.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.