Lily's Homework

  • + 1 comment

    Simple solution: number of elements - number of cycles

    Obviously getting the "beautiful array" is finding the minimum number of swaps to get a sorted array. But a curious idea (idk if it's the default idea to solve this).

    An interesting way to look at this: "Find number of connected components in a graph". In this case, every connected component is actually a cycle.

    We will connect every node N to the node M that stared where N will be at the end of the sorting. Like n.end_position === m.start_position:

    1-node cycle: the element is already in its final position

    2-node cycle: in the end, the element N will have changed positions with element M

    N-node cycle: a chain in which every node would change positions with the next.

    And the number of swaps internal to a cycle is: n (number of elements in the cycle) - 1 So the final number will be: array.length - number_of_cycles