Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find all anagrams of a pattern in a string

Return start indices of all anagrams of a pattern inside a string using a sliding window.

Python practice14 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given a string s and a pattern p, find all start indices of p's anagrams in s. An anagram is a rearrangement of letters. Return a list of starting indices in ascending order. If none exist, return an empty list. Assume s and p contain only lowercase English letters.

Task

Use a fixed-size sliding window and character frequency comparison to locate all anagram starting indices in linear time.

Examples

Basic example

Input

s = 'cbaebabacd', p = 'abc'

Output

[0, 6]

Substrings 'cba' at index 0 and 'bac' at index 6 are anagrams of 'abc'.

Input format

Two strings s and p.

Output format

A list of integers representing start indices (e.g. [0, 6]).

Constraints

0 <= len(s), len(p) <= 10^5. Only lowercase English letters. Expected time O(n).

Samples

Sample 1

Input

s = 'abab', p = 'ab'

Output

[0, 1, 2]

All substrings starting at 0,1,2 are anagrams of 'ab'.