![]() |
VOOZH | about |
Given an array of n positive integers and a number k. Find the minimum number of swaps required to bring all the numbers less than or equal to k together.
Examples:
Input: arr[] = {2, 1, 5, 6, 3}, k = 3
Output: 1
Explanation: To bring elements 2, 1, 3 together, swap arr[2] with arr[4]. Final array will be arr[] = {2, 1, 3, 6, 5}Input: arr[] = {2, 7, 9, 8, 5, 7, 4}, k = 5
Output: 1
Explanation: To bring elements 2, 5 and 4 together, swap arr[0] with arr[5]. Final array will be arr[] = {7, 7, 9, 8, 5, 2, 4}.
Table of Content
A simple solution is to first count all elements less than or equal to k(say 'good'). Now traverse for every subarray of size good and swap those elements whose value >k with those whose value <= k and are not included in the subarray. The time complexity of this approach is O(N * K).
The idea is to find the number of elements which are <=k, (say 'good'). This means that we need a subarray of size 'good' with all the elements <= k. So, for every window of size 'good', swap elements in the subarray which are greater than k with elements not included in the subarray and are <= k, to find the minimum swaps. For this, we can maintain a sliding window of size 'good' and for each of the sliding window calculate the minimum swaps by finding the count of elements > k, say ('bad') in the window. Minimum swaps among all the sliding windows will be the answer.
Below is the implementation of the above approach:
1
Working of the above approach:
Complexity Analysis: