I am solving a hackerrankHackerRank problem called 'Morgan and a String'. Given two strings, each consisting of up to 105 uppercase characters, the task is to form the lexicographically smallest string from those letters by taking either of the first remaining character from the strings at each step. Example, for input strings "ACA" and "BCF", the answer should be "ABCACF":
Jack Daniel Result
ACA BCF
CA BCF A
CA CF AB
A CF ABC
A CF ABCA
F ABCAC
ABCACF
Sample input, with one test case:
1
ACEG
BDFH
Output:
ABCDEFGH
I've solved it by writing my own code which works perfectly on smaller test cases.But But when they run it against test cases which are approx 6000 characters long, So I get a runtime error.
Below is my code:
n=int(input())#number of pairs to input
for mn in range(n):
a=input()# String1 in the pair
b=input()#String2 in the pair
la=[]
lb=[]
for i in range(max(len(a),len(b))):#creating lists with all possible elements by slicing off the characters
la.append(a[i:])
lb.append(b[i:])
if len(a)>len(b):#removes empty elements
lb=[x for x in lb if x!='']
else:
la=[x for x in la if x!='']
while True:#Create empty list for sorting the 0th elements of 'la' nd 'lb'
temp=[]
temp.append(la[0])
temp.append(lb[0])
temp=sorted(temp)
print(temp[0][0],end='')#print the 1st character
if(temp[0] in la):#removing the element after printing the first character
la.pop(0)
else:
lb.pop(0)
if len(la)==0:#breaks the while loop if a list gets empty
print(temp[1],end='')
break
elif len(lb)==0:
print(temp[1],end='')
break
Following are the sample input and output:
ip:1 aceg bdfh
op:abcdefgh
How can I increasingincrease the efficiency?
n=int(input())#number of pairs to input
for mn in range(n):
a=input()# String1 in the pair
b=input()#String2 in the pair
la=[]
lb=[]
for i in range(max(len(a),len(b))):#creating lists with all possible elements by slicing off the characters
la.append(a[i:])
lb.append(b[i:])
if len(a)>len(b):#removes empty elements
lb=[x for x in lb if x!='']
else:
la=[x for x in la if x!='']
while True:#Create empty list for sorting the 0th elements of 'la' nd 'lb'
temp=[]
temp.append(la[0])
temp.append(lb[0])
temp=sorted(temp)
print(temp[0][0],end='')#print the 1st character
if(temp[0] in la):#removing the element after printing the first character
la.pop(0)
else:
lb.pop(0)
if len(la)==0:#breaks the while loop if a list gets empty
print(temp[1],end='')
break
elif len(lb)==0:
print(temp[1],end='')
break