VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-swaps-required-bring-elements-less-equal-k-together/

⇱ Minimum swaps required to bring all elements less than or equal to k together - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum swaps required to bring all elements less than or equal to k together

Last Updated : 17 Dec, 2024

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}.

[Naive Approach] Finding all subarrays - O(N * K) Time and O(1) Space

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).

[Expected Approach] Using Fixed-Size Sliding Window - O(N) Time and O(1) Space

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:


Output
1

Working of the above approach:


Complexity Analysis:

  • Time Complexity: O(n), where n is the size of input array arr[]
  • Auxiliary Space: O(1)
Comment
Article Tags: