Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can\'t be rearranged it can be put
After I grasped what you're after, here's a possible solution
Partition your array
[1,1,1,8,8,8,2,3,3,4,1,1,1,2,2] -> [[3,1],[3,8],[1,2],[2,3],[1,4],[3,1],[2,2]]
(read 3 times 1, 3 times 8, and so on)
For each partition entry i with p[i][0] >1 (times >1):
Choose a "valid" position j (so p[j][1] != p[i][1] && p[j+1][1] != p[i][1])
Decrement p[i][0] element and insert [p[i][1],1] in partition at position j
or leave it out if there is no such position.
This should have linear time complexity (book-keep valid positions for each number).