Find All Anagrams in a String

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An anagram is a rearrangement of all characters in a string.

Examples

Example 1:

Input: s = "cbaebabacd", p = "abc"

Output: [0, 6]

Explanation: The substring starting at index 0 is "cba", which is an anagram of "abc". The substring starting at index 6 is "bac", which is also an anagram of "abc".

Example 2:

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

Output: [0, 1, 2]

Explanation: The substring starting at index 0 is "ab", at index 1 is "ba", and at index 2 is "ab". All are anagrams of "ab".

Example 3:

Input: s = "aaaaaaaaaa", p = "aaaa"

Output: [0, 1, 2, 3, 4, 5, 6]

Explanation: Every substring of length 4 in s is "aaaa", which is an anagram of p.

Constraints

  • 1 <= s.length, p.length <= 3 * 10⁴
  • s and p consist of lowercase English letters only.
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle