Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find all start indices of pattern anagrams

Return all starting indices of p's anagrams in s using sliding window and frequency counting.

Python practice15 minStrings – Sliding Window & FrequencyIntermediateLast updated March 25, 2026

Problem statement

Given two strings s and p, return a list of all start indices of p's anagrams in s. An anagram is a permutation of the pattern. The order of output indices does not matter. Use a sliding window and frequency counting to achieve O(n) time complexity.

Task

Use a fixed-size sliding window plus frequency counts to detect anagrams of a pattern within a text string.

Examples

Basic example

Input

s = "cbaebabacd", p = "abc"

Output

[0, 6]

The substring at index 0 is "cba" which is an anagram of "abc". The substring at index 6 is "bac" which is also an anagram.

Input format

Two string arguments: s (text) and p (pattern). Example: find_anagrams("cbaebabacd", "abc")

Output format

A list of integers representing starting indices. Example: [0, 6]

Constraints

0 <= len(s), len(p) <= 10^5. Only ASCII lowercase letters assumed for typical inputs, but solution should work with general characters.

Samples

Sample 1

Input

s = "abab", p = "ab"

Output

[0, 1, 2]

All substrings "ab","ba","ab" are anagrams of "ab" at indices 0,1,2.