A rack holds n items with distinct integer labels in some order. In one move you may swap any two items (not necessarily adjacent). Report the minimum number of swaps needed to arrange the labels in strictly ascending order.
Line 1: an integer n.
Line 2: n space-separated distinct integers, the labels in their current order.
A single integer: the minimum number of swaps to sort the labels ascending.
Example 1
Input
4 3 1 2 4
Expected
2
Explanation
Swap 3 and 1 to get 1 3 2 4, then swap 3 and 2 to get 1 2 3 4: 2 swaps, which is minimal.
Example 2
Input
3 1 2 3
Expected
0
Explanation
Already sorted, so 0 swaps are needed.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →