We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
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