oneby7

Sliding Window Fixed-size window

181. Find All Anagrams in a String

Medium

You are given two strings, text and pattern. Return every index of text where a rearrangement of pattern starts. If there is none, return an empty list.

A rearrangement of pattern holds exactly the same letters as pattern, each one the same number of times, in any order. pattern itself counts as one of its rearrangements. A match must be a block of letters that sit next to each other in text, and two matches may overlap.

You may return the indexes in any order. The output shows them from smallest to largest.

Example 1

Input: text = "meatteamate", pattern = "tame"

Output: [0,4,7]

Explanation: The blocks "meat" at index 0, "team" at index 4 and "mate" at index 7 each hold one t, a, m and e. Every other block of four letters holds a t or an a twice.

Example 2

Input: text = "abab", pattern = "ba"

Output: [0,1,2]

Explanation: Every block of two letters holds one a and one b, so all three starts count. The matches overlap, and that is allowed.

Example 3

Input: text = "dog", pattern = "good"

Output: []

Explanation: pattern has four letters and text has only three, so no block of text is long enough.

Check your understanding

Work out the answer for this input before you write any code.

text = "aabaa", pattern = "aab"

Constraints

  • 1 ≤ text.length, pattern.length ≤ 105
  • text and pattern hold lowercase English letters only.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.