We have to choose lexicographically smallest S.

**aaaka**eekmnnry < **akaaa**eekmnnry

and in the test case

1

deadzacrosdead

dad

aac**daddd**eeorsz < aac**dddad**eeorsz

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.

@fallmount @coder_indian4

You can do the following changes in your code after your final sorted list

```
np=len(pattern)
flag=1
for k in range (1,np):
if(p[k]<p[0]):
flag=0
break
if(p[k]>p[0])
break
```

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
if (flag==0):
pos=0
for i in range(0,len(s)):
if (s[pos] == p[0]):
index = s.index[p]
s[pos],s[index] = s[index],s[pos]
#swapping pattern with first occurance of p[0]
```