Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Strings
Amazon
Google
Find All Anagrams In A String

Find every starting index where a substring is an anagram of a given pattern string.

Acceptance 100%
Problem Statement

Problem

Given two strings s and p, return all starting indices in s where the substring of length |p| is an anagram of p.

A substring is an anagram of p if it uses exactly the same characters with the same frequencies, possibly in a different order.

Notes

  • Indices are 0-based.
  • Return the indices in increasing order.
  • If no substring matches, return an empty list.

Input Format

  • A string s
  • A string p

Output Format

  • An array of integers representing all valid starting indices

Constraints

  • 1 <= |s|, |p| <= 10510^{5}
  • s and p typically contain lowercase English letters
  • Time-efficient solutions should avoid checking each substring from scratch
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "cbaebabacd", p = "abc"

Output

[0,6]

Explanation

The substrings starting at indices 0 ("cba") and 6 ("bac") are anagrams of "abc".

Example 2

Input

s = "abab", p = "ab"

Output

[0,1,2]

Explanation

The substrings "ab", "ba", and "ab" are all anagrams of "ab".

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.