This is an interview question. A swap means removing any element from the array and appending it to the back of the same array. Given an array of integers, find the minimum number of swaps needed to sort the array.
Is there a solution better than O(n^2)?
For example:
Input array: [3124].
The number of swaps: 2 ([3124] -> [1243] -> [1234]).
This might work in
O(nlogn)even if we don’t assume array of consecutive values.If we do – it can be done in
O(n).One way of doing it is with
O(n)space andO(nlogn)time.Given array
Asort it (O(nlogn)) into a second arrayB.now… (arrays are indexed from 1)