I need to find the minimum amount of swaps required to sort a string that only has letters X, Y and Z in random order and amount (not only adjacent). Any two chars can be swapped.
For example the string ZYXZYX will be sorted in 3 swaps: ZYXZYX -> XYXZYZ -> XXYZYZ -> XXYYZZ ZZXXYY - in 4 swaps, XXXX - in 0 swaps.
So far I have this solution, but the sorting does not sort the chars in the optimal way, so the result is not always the very minimum amount of swaps. Also, the solution should be O(nlogn).
def solve(s):
n = len(s)
newS = [*enumerate(s)]
sortedS = sorted(newS, key = lambda item:item[1])
counter = 0
vis = {v:False for v in range(n)}
print(newS)
print(sortedS)
for i in range(n):
if vis[i] or sortedS[i][0] == i:
continue
cycle_size = 0
j = i
while not vis[j]:
vis[j] = True
j = sortedS[j][0]
cycle_size += 1
if cycle_size > 0:
counter += (cycle_size - 1)
return counter