Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Substring Anagrams

Given a string s and a pattern string p, return the starting indices of all substrings of s that are anagrams of p. You may return the answer in any order.

An anagram of p is any rearrangement of its characters, so a matching substring must have exactly the same length as p and the same multiset of characters (same letters, same counts, order does not matter).

Example 1:

Input: s = "cbaebabacd", p = "abc"
Output: [0, 6]
Explanation: The substring starting at index 0 is "cba", an anagram
of "abc". The substring starting at index 6 is "bac", also an
anagram of "abc".

Example 2:

Input: s = "abab", p = "ab"
Output: [0, 1, 2]
Explanation: "ab", "ba", and "ab" starting at indices 0, 1, and 2 are
all anagrams of "ab".

Constraints:

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

Share this question

← Back to Sliding Windows practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.