Assuming:
- The array elements are the integers 1 to N.
Steps:
- Allocate a second (histogram) array H of length N.
- In a single pass through the initial array A, for each index i increment H[ (A[i] - i) % N]
- In a single pass through H, identify the element R of H with the maximum count
- Clear H.
- Identify the number of Orbits in the original array under a rotation by R. (by stepping forward through H until H[i]=0, then stepping through the orbit for which A[i] is a member under the rotation R) setting H[i]=1 for each member of the orbit, and repeating until the element H[N-1] has been processed (counting the nubmer of orbits as you go). This is also O(N) as each element of A is visited exactly once.
- The required number of swaps = N - Orbits.
This is O(N).
Update: I have updated the algorithm to account for multiple orbits. In processing each orbit, the final swap places two elements instead of just 1.
I suspect that the number of Orbits is invariant under any rotation, which would simplify the algorithm considerbly but would not affect it's complexity, which remains at O(N).