Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted array by above swap condition then print not possible.
Input : arr = [1, 2, 5, 3, 4] Output : 2 We can reach to above-permuted array in total 2 swaps as shown below, [1, 2, 3, 4, 5] -> [1, 2, 3, 5, 4] -> [1, 2, 5, 3, 4] Input : arr = [5, 1, 2, 3, 4] Output : Not Possible It is not possible to reach above array just by swapping numbers 2 positions left to it.
We can solve this problem using inversions. As we can see that if a number is at a position which is more than 2 places away from its actual position then it is not possible to reach there just by swapping with elements at 2 left positions and if all element satisfy this property (there are <=2 elements smaller than it on the right) then answer will simply be total number of inversions in the array because that many swaps will be needed to transform the array into permuted array.
We can find the number of inversions in N log N time using merge sort technique explained here so total time complexity of solution will be O(N log N) only.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum number of swaps required to sort an array | Set 2
- Minimum number of swaps required to sort an array
- Minimum adjacent swaps required to Sort Binary array
- Number of swaps to sort when only adjacent swapping allowed
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Minimum Swaps required to group all 1's together
- Minimum swaps to make two arrays identical
- Minimum swaps so that binary search can be applied
- Minimum swaps required to bring all elements less than or equal to k together
- Minimum number of swaps required for arranging pairs adjacent to each other
- Minimum number of adjacent swaps for arranging similar elements together
- Lexicographically smallest array after at-most K consecutive swaps
- Largest lexicographic array with at-most K consecutive swaps
- Check if the array can be sorted using swaps between given indices only
- Largest permutation after at most k swaps
Improved By : Rajput-Ji