How do we rearrange elements in an array so that no two adjacent elements are the same?

I want to sort the elements that are the same in the array so that they do not come one after the other.

E.G

Input*: [‘A’,’A’,’A’,’B’,’B’,’B’,’C’,C’]

Output: [‘B’,’A’,’C’,’B’,’A’,’C’,’B’,’A’]

I tried the solution here it works most of the time but not always :
https://www.geeksforgeeks.org/rearrange-numbers-in-an-array-such-that-no-two-adjacent-numbers-are-same/

E.G

Input: [‘A’, ‘A’, ‘A’, ‘A’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘B’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’, ‘C’]

Output: Not valid Array

How do I get it to work in all situations?

I’ve seen similar questions but couldn’t find a clear answer.

Thank you in advance for your help.