DSA AnimatorREVISION VIDEOS
← Back to problems
New

Find All Anagrams in a String — LeetCode 438 video explanation

You get two strings, s and p. Find every start index in s where an anagram of p begins.

Loading videos…

DSA Animator › DSA Revision › Strings › Find All Anagrams in a String

Key moments in the Find All Anagrams in a String video

0:04Problem0:10Example0:22Brute force0:30Key idea0:43Dry run1:11Code1:31Takeaway

What you will learn

Remember: anagram windows are fixed windows with matching counts. Update two counts per step instead of recounting. The video solves Find All Anagrams in a String (LeetCode 438, Medium) with the Fixed Sliding Window pattern from the Strings topic, and you can replay every step in the interactive Find All Anagrams in a String animation.

Find All Anagrams in a String video transcript

Problem

You get two strings, s and p. Find every start index in s where an anagram of p begins.

Example

s is c b a e b a b a c d, and p is a b c. Index 0 holds c b a, and index 6 holds b a c. Both are anagrams of a b c, so the answer is 0 and 6.

Brute force

Taking three letters at every index and sorting them repeats the same work again and again. If p is long, that becomes very slow.

Key idea

Keep a fixed window, as long as p. Count the letters of p once. Each time the window slides one step, one letter comes in, and one letter goes out. Update just those two counts, and check whether the counts match.

Dry run

The counts of p are a 1, b 1 and c 1. The first window, c b a, has equal counts, so index 0 goes into the answer. Slide forward: c leaves and e enters, giving b a e, which does not match. Then a e b, e b a, b a b, and a b a, and none of them match. Then a leaves and c enters, giving b a c, which matches, so index 6 goes into the answer. The last window, a c d, does not match. The answer is 0 and 6.

Code

In code, keep two count arrays of 26, one for p and one for the window. At each step, add the new letter, and once the window is too big, remove the oldest letter. If the two arrays are equal, add the start index of the window to the answer. Each comparison is 26 checks, so time is O of n, and space is O of 1.

Takeaway

Remember: anagram windows are fixed windows with matching counts. Update two counts per step instead of recounting.

More Strings revision videos

← All 185 DSA revision videos