We have to choose lexicographically smallest S.
aaakaeekmnnry < akaaaeekmnnry
and in the test case
aacdadddeeorsz < aacdddadeeorsz
Hope you get the logic behind this, I’m really bad at explaining
@cerr has explained it above.
You can also refer to the editorial.
You can do the following changes in your code after your final sorted list
for k in range (1,np):
Now if flag==1 then your codes will work fine since the sorted list will give the expected output.
For flag equals zero,
#Lets say s is your final list after sorting
for i in range(0,len(s)):
if (s[pos] == p):
index = s.index[p]
s[pos],s[index] = s[index],s[pos]
#swapping pattern with first occurance of p