Menu Close

Rearrange characters such that no two adjacent are same ….Python[FTC]

Rearrange characters in a string such that no two adjacent are same.
Given a string str, rearrange the characters of s so that any two adjacent characters are not the same.

Return any possible rearrangement of str or return ” ” if not possible.

Input:  aaabc

Output: acaba
def reorStr(str):
    if(len(str) == 0) :
        return ''

    d,L={},[]
    str=list(str)

    for i in str:
        if i not in d: d[i]=1
        else: d[i]+=1

    d=sorted(d.items(),reverse=True,key=lambda x:x[1])

    for i in range(len(d)):
        d[i]=list(d[i])

    for j in d:
        j[0],j[1]=j[1],j[0]

    j=0
    d=sorted(d,reverse=True)

    for i in range(len(str)*2):
        if j<=1 and j<len(d):
            if d[j][0]>0:
                L.append(d[j][1])
                d[j][0]-=1
            j+=1
        else:
            j=0
            d=sorted(d,reverse=True)

    str=L
    flag=0

    for i in range(len(str)):
        if(i==0):
            if(str[i]==str[i+1]):
                flag+=1
        elif(i==len(str)-1):
            if(str[i]==str[i-1]):
                flag+=1
        else:
            if(str[i]==str[i+1] or str[i]==str[i-1]):
                flag+=1
    return ''.join(str) if flag==0 else ''

STRING=input('Enter any string: ')
print(reorStr(STRING))

 


INPUT_1:
Enter any string:  aaabc

OUTPUT:
  acaba


INPUT_2:
Enter any string:  aaabb

OUTPUT:
  ababa


INPUT_3:
Enter any string:  aa

OUTPUT:
  ” “


 


INPUT_4:
Enter any string:  aaaabc

OUTPUT:
  ” “


INPUT_5:
Enter any string:  aab

OUTPUT:
  aba


INPUT_6:
Enter any string:  bbbbbbb

OUTPUT:
  ” “


ILLUSTRATION

EXECUTED USING PYTHON3