DSA Trainer
Sliding Window
← All problems
PremiumSliding WindowMedium

Find All Anagrams in a String

Asked at:AmazonGoogleMicrosoft

Given two strings s and p, return a list of all starting indices in s where a rearrangement of p begins. The rearrangements don't need to look identical, any ordering of p's characters counts.

This is a premium problem.

Unlock Find All Anagrams in a String with the full guided learning path and every other premium problem.

Problem

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

Input

Two strings `s` and `p`, containing only lowercase English letters.

Output

A list of starting indices (0-indexed) in `s` where a permutation of `p` starts. Return in any order.

Examples

Input: s = "cbaebabacd", p = "abc"

Output: [0, 6]

At index 0: "cba" is a rearrangement of "abc". At index 6: "bac" is a rearrangement of "abc".

Input: s = "abab", p = "ab"

Output: [0, 1, 2]

"ab" at 0, "ba" at 1, "ab" at 2, all rearrangements of "ab".

Input: s = "af", p = "be"

Output: []

No substring of s has the same characters as p.

The brute-force approach

For each starting index i in s, extract the substring of length len(p) and check whether it's an anagram of p by sorting both and comparing.

result = []
sorted_p = sorted(p)

for i in range(len(s) - len(p) + 1):
    window = s[i : i + len(p)]        # ← extract substring
    if sorted(window) == sorted_p:    # ← sort and compare: O(k log k)
        result.append(i)

return result

Sorting a window of length k costs O(k log k), and you do it for every position in s, so the total is O(n × k log k). For a pattern of length 26, that's already slow, and every new starting index requires sorting the window from scratch. The insight is that sliding the window one step right only changes two characters: one falls off the left, one enters from the right. You don't need to re-sort everything.

Time: O(n × k log k)Space: O(k)

Spotting the pattern

This is a Sliding Window problem. The key question to ask yourself:

How do I check every length-k window of s against p without re-examining all k characters at each position?

Answering that is where it clicks, and it's exactly what the guided walkthrough below builds with you: the pattern reasoning, a progressive hint ladder that never spoils the answer, a row-by-row dry run, the optimized solution, and an in-browser editor to run your code against real test cases.

Premium

Unlock the full guided solution

The Sliding Window walkthrough for Find All Anagrams in a String: the progressive hint ladder, a row-by-row dry run, the optimized code, and an in-browser runner, plus the full guided learning path and every other premium problem.

Already finished Big-O and Hash Maps free? This picks up right where the path leads: same format, harder patterns, the ones that show up in every FAANG-style screen.

What you get

  • The full guided learning path: concept lessons, drills, graded tests, and cold-read capstones for every pattern
  • Stop going blank on algorithm problems. The hint ladder walks you to the answer without spoiling it.
  • Actually internalize the trace: dry runs walk state row by row so it clicks before you write a line
  • Know when to reach for each pattern. Every problem names the trigger so you spot it next time.
  • Write and run JS or Python in the browser with real test cases on every problem
  • Access every new problem, unit, and pattern guide as they ship weekly
B
Big_Wolverine_7575Founding Member· unprompted on Reddit

“This app finally made it click. I tried NeetCode, CTCI, and YouTube for years and still couldn't solve Two Sum. The beginner mental models for the patterns are genuinely so helpful. THANK YOU.

Price locks in for life · First 100 only

Founding Member Deal

$29 / year

or $6 / month

LeetCode Premium is $159/year and doesn't teach you anything.

Less than one Udemy course, with guided problems instead of passive lectures.

One extra month of job searching costs more than a full year here.

Your price is locked in for life.

When the 100th founding spot closes, the price goes up for everyone who joins after. Your rate never changes, no matter how much the curriculum grows.

  • The full guided learning path, every unit
  • All 150 problems across 33 patterns, plus every new one
  • New problems and units weekly
  • Cancel anytime

Cancel anytime. Not useful within 7 days? Email for a full refund. Secured by Stripe.