Skip to content
BytePatterns

Anagram Positions in a Text

MediumStrings#fixed-sliding-window#frequency-count~25m

Problem

A plagiarism checker looks for scrambled copies of a short key inside a long text. Given lowercase strings text and key, return every start index i where the len(key) letters of text starting at i form an anagram of key, meaning they use exactly the same letters the same number of times. List the indices in ascending order. Both strings have up to 30,000 letters, so re-counting every window from scratch is too slow.

Examples

Input:  text = "cbaebabacd", key = "abc"
Output: [0, 6]
Why:    "cba" starts at 0 and "bac" starts at 6
Input:  text = "abab", key = "ab"
Output: [0, 1, 2]
Why:    windows may overlap: "ab", "ba", "ab"
Input:  text = "a", key = "ab"
Output: []
Why:    edge case, the key is longer than the text

Hints

0 / 3

Stuck on the idea rather than the code? Sliding Window covers it.