Letters Rearranged Somewhere Inside

EasySliding Window≈ 25 min

You are given a word and a text. Find a place in the text where the word's letters stand next to each other in any order: a stretch of the text, exactly as long as the word, that uses the same letters the same number of times. Return the index where the first such stretch starts, or -1 if there is none.

Both strings hold only lowercase letters a–z, and spaces in the text.

Examples

text
word = "ab", text = "eidbaooo"         →  3
word = "ab", text = "eidboaoo"         →  -1
word = "tea", text = "the eat"         →  4
word = "listen", text = "enlists"      →  0

In the first example "ba" starts at index 3. In the second, the b and the a are never next to each other. In the last, "enlist" uses the letters of "listen".

Constraints

  • The word holds between 1 and 20,000 letters, the text between 0 and 20,000 characters.
  • Aim for O(n) in the length of the text: counting the letters of every stretch from scratch costs n × m.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.