title: Minimum adjacent swaps to group equal elements in an array
body: <p>Given an array L containing N elements, from an alphabet of M distinct elements, is there an effective way to calculate the minimum number of swaps of two adjacent elements such that we group all the equal elements together, knowing that for any index i in [1, n], there is less than 9 distinct elements e from M such that there exists j &gt; i and k &lt; i for which L[j] = L[k] = e (so for any position in the array, there is less than 9 groups that have at least an element before, and one after)</p>
  <p>For example, given an array L = {1, 2, 3, 1, 2, 3, 2, 2, 1}, we want to arrive at {1,1,1,2,2,2,2,3,3} or {2,2,2,2,3,3,1,1,1} etc...</p>
  <p>This problem is also equivalent to finding an optimal order for the elements of M. If we can find such an order, the problem can be solved by simply finding the minimum number of swaps to sort the array given that order, which can be done in O(NlogN) (see <a href="https://stackoverflow.com/questions/20990127/sorting-a-sequence-by-swapping-adjacent-elements-using-minimum-swaps">here</a>).</p>