Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find all anagrams in a string

Find all start indices of p's anagrams in s using a sliding window and frequency counting.

Python practice17 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

Given two strings s and p, return a list of all start indices of p's anagrams in s. You may return the answer in any order. An anagram is a permutation of characters. Use a sliding window of length len(p) and maintain counts to detect when the window contains an anagram of p. The output list should be sorted in ascending order (to make testing deterministic).

Task

Use fixed-size sliding window with character counts (hashing) to efficiently detect anagram occurrences in O(n) time.

Examples

Example with two matches

Input

s = 'cbaebabacd', p = 'abc'

Output

[0, 6]

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

Input format

Two strings s and p. Both consist of lowercase letters.

Output format

A list of starting indices (integers) where each index marks the start of an anagram of p in s.

Constraints

0 <= len(s), len(p) <= 10^5. Only lowercase English letters. Aim for O(len(s) + len(p)) time.

Samples

Sample 1

Input

s = 'abab', p = 'ab'

Output

[0, 1, 2]

Windows 'ab','ba','ab' are all anagrams of 'ab'.