Skip to content
Decoder

Find All Anagrams in a String

Medium

Problem

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.

Example 1

Input
s = "cbaebabacd", p = "abc"
Output
[0, 6]
Why
"cba", "bac"

Example 2

Input
s = "abab", p = "ab"
Output
[0, 1, 2]

Example 3

Input
s = "a", p = "ab"
Output
[]

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.