Smallest KMP | Solutions SKMP

Smallest KMP SOLUTION

Smallest KMP Gourmet specialist has a string S. He likewise has another string P, called design. He needs to discover the example in S, however that may be unthinkable. Thusly, he is eager to reorder the characters of S so that P happens in the subsequent string (a re-arranged word of S) as a substring.
Since this issue was excessively hard for Chef, he chose to ask you, his virtuoso companion, for help. Would you be able to discover the lexicographically littlest re-arranged word of S that contains P as substring?
Note: A string B is a substring of a string An if B can be gotten from A by erasing a few (conceivably none or all) characters from the earliest starting point and a few (potentially none or all) characters from the end.
Information
The primary line of the info contains a solitary number T indicating the quantity of experiments. The portrayal of T experiments follows.
The main line of each experiment contains a solitary string S.
The subsequent line contains a solitary string P.
Yield
For each experiment, print a solitary line containing one string ― the littlest re-arranged word of S that contains P.
Limitations
1≤T≤10
1≤|P|≤|S|≤105
S and P contain just lowercase English letters
there is at any rate one re-arranged word of S that contains P
Subtasks
Subtask #1 (20 focuses): |S|≤1,000
Subtask #2 (80 focuses): |S|≤105
Model Input
3
akramkeeanany
otherwise known as
supahotboy
bohoty
daehabshatorawy
badawy
Model Output
aaakaeekmnnry
abohotypsu
aabadawyehhorst

Solution

 

CODE Python3.6 :

def cmpr(a,b):

    n1,n2=len(a),len(b)

    for i in range(min(n1,n2)):

        if a[i]<b[i]:

            return 1

        elif a[i]>b[i]:

            return 0

    return 0    

t=int(input())

for i in range(t):

    st=input()

    pat=input()

    dicp={}

    for k in pat:

        try:

            dicp[k]+=1

        except:

            dicp[k]=1

    remd=[0 for i in range(26)]

    for k in st:

        if k not in dicp or dicp[k]==0:

            remd[ord(k)-ord(‘a’)]+=1

        else:

            dicp[k]-=1

    ans=””

    if len(pat)>1 and cmpr(pat[0]+pat,pat+pat[0])==1:

        tmp=ord(pat[0])-ord(‘a’)

        for k in range(tmp+1):

            ans+=chr(ord(‘a’)+k)*remd[k]

        ans+=pat

        for k in range(tmp+1,26):

            ans+=chr(ord(‘a’)+k)*remd[k]

    else:

        tmp=ord(pat[0])-ord(‘a’)

        for k in range(tmp):

            ans+=chr(ord(‘a’)+k)*remd[k]

        ans+=pat

        for k in range(tmp,26):

            ans+=chr(ord(‘a’)+k)*remd[k]

    print(ans) 

Leave a Comment