This website uses cookies to enhance the user experience

Find All Anagrams in a String

Difficulty: 🔥 Hard

Problem Statement

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. The order of output does not matter.

Example
Input: s = 'cbaebabacd', p = 'abc'
Output: [0, 6]
Explanation: The substring 'cba' starting at index 0 and 'bac' starting at index 6 are anagrams of 'abc'.
Input: s = 'abab', p = 'ab'
Output: [0, 1, 2]
Explanation: The substring 'ab' starting at index 0, 'ba' starting at index 1, and 'ab' starting at index 2 are anagrams of 'ab'.
Constraints
  • The input strings only contain lowercase English letters.
  • The length of both strings will not be larger than 20,100.

Expected Challenge Output

When the function findAnagrams is called with the given example inputs, the expected outputs are:

  • For the input s = 'cbaebabacd', p = 'abc', the output is [0, 6].
  • For the input s = 'abab', p = 'ab', the output is [0, 1, 2].

console.log(findAnagrams('cbaebabacd', 'abc'));  // Output: [0, 6]
console.log(findAnagrams('abab', 'ab'));  // Output: [0, 1, 2]
function findAnagrams(s, p) {
// YOUR SOLUTION HERE
}

Memory: 0

CPU: 0