Help with problem SKMP, August Long Challenge 2020

Can anyone please help me find out mistake in my code logic? This is the code i tried for the problem, The sample tests cases works fine but all tasks of submission gives WA (Wrong Answer) as the result. I cannot find whats wrong with my logic.

def solution():
    s = input()
    p = input()

    #if the pattern is of same length as string given return the pattern
    if len(s) == len(p):
        return p

    s = list(s)

    temp = list(p) #copy of pattern

    # finding and removing characters present in the pattern from the string
    i = 0
    while(i<len(s)):
        # print(s, temp)
        if s[i] in temp:
            temp.remove(s[i])
            s.pop(i)
        else:
            i+=1

    # Sorting the remaining string
    s.sort()

    new_string = ''

    # attaching the pattern at the point where the first character of pattern is greater than sorted string and joining the remaing part of sorted sting
    for i in range(len(s)):
        if s[i] > p[0]:
            new_string = new_string + p + ''.join(s[i:])
            return new_string

        else:
            new_string += s[i]

    new_string += p
    return new_string



tests = int(input())
for _ in range(tests):
    print(solution())