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
Morae! Q
- Find a triplet such that triplet is minimum of all the triplets.
- Rearrange characters in a string such that no two adjacent are same.
- Return the coordinates of all cells in matrix sorted by their distance.
- Function to verify the ISBN number from the book.
- Find out the absolute difference of values of two array integers.
- Rotate the array in the right direction by K steps.
- Find the sequence of moves that wins the game, collect exactly G coins!.
- Calculate the sum of boundary elements of a matrix.
- Find the total number of ways to reach the tree house.
- Compute profit and loss of a product.
- Find the total expense of purchased items.
- Determine the maximum sequence weight.
- Find the person’s birth year is a leap year or not.
- Find the inner rating with the displayed rating.
- Find if angles are valid to form a triangle.
- Find out the winner of the game from the given statistics.
- Verify the tag to determine if one needs to arrest or allow the vehicle.
- Find the largest hexadecimal number.
- Group up all anagrams together from given words.
- Return all anagrams from the given words.