All problems

Problem 60

Find All Anagrams in a String

Medium · 20 pts · String, Sliding Window, Hash Table

Problem

You are given two strings S and P. Find every position in S where a substring of length |P| is an anagram of P, that is, it contains exactly the same letters as P with the same counts. Print the zero-based start positions in increasing order, or -1 if there are none. Slide a window of length |P| along S while keeping letter counts for the window. Moving the window by one adds one letter and removes one, so each step takes constant time, and the window is an anagram whenever its counts equal those of P.

Input

Two lines: string S and string P (lowercase letters).

Output

Print the zero-based start indices in increasing order, space-separated, or -1 if there are none.

Constraints

1 <= |S|, |P| <= 100000

Example input

cbaebabacd
abc

Example output

0 6

Explanation

With P = "abc", the substring at index 0 of "cbaebabacd" is "cba" and the one at index 6 is "bac". Both use exactly one a, one b and one c, and no other window does, so the answer is 0 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Window Substring Next: Count Palindromic Substrings