Substring Permutation

Interview

Time limit1sMemory limit512 MB

Summary
Given strings S and P, decide whether some permutation of P is a substring of some permutation of S.
Level

Medium6 of 10

Topics
Hash map, Two pointers, Array
Solved
No attempts yet

Problem

Given two strings SS and PP, there are several ways to determine whether PP appears as a substring of SS. The simplest is to check directly whether PP equals any substring of SS. Since SS can have O(∣S∣)O(|S|) substrings of length ∣P∣|P|, this approach takes O(∣S∣×∣P∣)O(|S| \times |P|) time. A more sophisticated method uses the Knuth-Morris-Pratt (KMP) algorithm to solve the problem in O(∣S∣+∣P∣)O(|S| + |P|).

This problem poses a similar challenge.

Given two strings SS and PP. Let Π(S)\Pi(S) be the set of all strings that are permutations of SS, and Π(P)\Pi(P) the set of all strings that are permutations of PP. Determine whether there exists a string p∈Π(P)p \in \Pi(P) and a string s∈Π(S)s \in \Pi(S) such that pp appears as a substring of ss.

For example, let S=guruS = \text{guru} and P=rugP = \text{rug}. Then Π(S)={gruu,guru,guur,rguu,rugu,ruug,ugru,ugur,urgu,urug,uugr,uurg}\Pi(S) = \{\text{gruu}, \text{guru}, \text{guur}, \text{rguu}, \text{rugu}, \text{ruug}, \text{ugru}, \text{ugur}, \text{urgu}, \text{urug}, \text{uugr}, \text{uurg}\}, and Π(P)={gru,gur,rgu,rug,ugr,urg}\Pi(P) = \{\text{gru}, \text{gur}, \text{rgu}, \text{rug}, \text{ugr}, \text{urg}\}. The string rug\text{rug} in Π(P)\Pi(P) appears as a substring of the string rugu\text{rugu} in Π(S)\Pi(S), that is, [rug]u[\text{rug}]\text{u}. In this example you can also find other pairs that satisfy the requirement, such as ⟨gru,gruu⟩\langle\text{gru}, \text{gruu}\rangle, ⟨gru,ugru⟩\langle\text{gru}, \text{ugru}\rangle, ⟨urg,uurg⟩\langle\text{urg}, \text{uurg}\rangle, ⟨gur,guru⟩\langle\text{gur}, \text{guru}\rangle.

Input

The input consists of two lines. The first line contains a string SS (1≤∣S∣≤1000001 \le |S| \le 100000). The second line contains a string PP (1≤∣P∣≤∣S∣≤1000001 \le |P| \le |S| \le 100000). Both SS and PP consist only of lowercase English letters (a-z).

Output

If there exists a string p∈Π(P)p \in \Pi(P) and a string s∈Π(S)s \in \Pi(S) such that pp appears as a substring of ss, output “YES” on one line. Otherwise, output “NO”. Do not print the quotes.

Examples4

  1. Example 1

    Input
    guru
    rug
    
    Expected output
    YES
    
  2. Example 2

    Input
    icpc
    inc
    
    Expected output
    NO
    
  3. Example 3

    Input
    yesorno
    sore
    
    Expected output
    YES
    
  4. Example 4

    Input
    indonesia
    icpcasia
    
    Expected output
    NO