Suppose you have a list of characters. Arrange the characters in the array in such a way that no two adjacent elements are the same.
Constraints No of characters~ 10^6
Sample Input - [‘c’, ‘d’, ‘d’, ‘a’, ‘a’, ‘x’ , ‘d’]
Sample Output - [‘a’, ‘d’, ‘x’, ‘c’, ‘d’, ‘a’, ‘d’]
My Try:
a = ['a', 'a', 'b', 'c', 'c', 'b', 'd']
import random
for c, d in zip(a, a[1:]):
if c != d:
continue
else:
random.shuffle(a):
print(a)
function to check if new array has distinct adjacent elements:
def distinctAdjacentElement(a, n):
m = dict()
for i in range(n):
if a[i] in m:
m[a[i]] += 1
else:
m[a[i]] = 1
mx = 0
for i in range(n):
if mx < m[a[i]]:
mx = m[a[i]]
if mx > (n+1) // 2:
return True
else:
return False