![]() |
VOOZH | about |
Given an unsorted permutation array of size N and an integer K ( 1 ≤ K ≤ N ), the task is to sort this permutation array in increasing order in the minimum number of steps, where in each step K elements have to be removed from the array and inserted at the front in increasing order and remaining elements should be in arbitrary order.
Examples:
Input: N = 5, P[] = [ 2, 4, 1, 5, 3 ], K = 2
Output: 2
Explanation: Following are the operations that can be performed to sort the permutation in increasing order.
- Operation1: Choose elements 3, 4 remove them from P then sort them in increasing order - 4, 3 and finally add them in front of P, So, P becomes [3, 4, 2, 1, 5].
- Operation 2: Choose elements 1, 2 remove them from P then sort them in increasing order - 1, 2 and finally add them in front of P, So P becomes [1, 2, 3, 4, 5}.
So the minimum number of operations required to sort the permutation P in increasing order is 2.
Input : N = 3, P[] = [3, 1, 2], K = 1
Output: 2
Explanation: Following are the operations that can be performed to sort the permutation in increasing order.
- Operation 1: Choose element 2 remove it from P then sort it in increasing order - 2 and finally add it in front of P, So P becomes [2, 3, 1].
- Operation 2: Choose element 3 remove it from P then sort it in increasing order - 1 and finally add it in front of P, So P becomes [ 1, 2, 3 ].
So the minimum number of operations required to sort the permutation P in increasing order is 2.
Approach: This can be solved by the following idea:
Suppose x elements do not participate in any operation means they are already sorted in increasing order. And since this x must be maximized to minimize the number of operations, we need to find the maximal subsequence of the numbers [...2, 1]. Let this sequence have w numbers, then the answer is ceil((n − w) / k).
Follow the steps to solve the problem:
Below is the implementation of the above approach:
2
Time Complexity: O(N)
Auxiliary Space: O(1)
By using the cycle: A cycle in a permutation is a sequence of elements that can be cyclically permuted, which means that the elements can be shifted to the right or left within the sequence without changing the order of the elements. For example, the permutation [3, 1, 4, 2] has two cycles: [3, 4, 2, 1] and [1].
This can sort the permutation by performing a series of cyclic permutations, where each cyclic permutation involves only elements that belong to the same cycle. In each cycle, sort the elements by performing a series of swaps. The number of swaps required to sort a cycle is equal to the length of the cycle minus one.
Follow the steps to solve the problem:
Below is the implementation of the above approach:
Minimum number of operations: 2
Time Complexity: O(N)
Auxiliary Space: O(N)