Minimum swaps required to bring all elements less than or equal to k together
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.
Input: arr[] = {2, 1, 5, 6, 3}, k = 3
Output: 1
Explanation: To bring elements 2, 1, 3 together, swap element ‘5’ with ‘3’ such that final array will be arr[] = {2, 1, 3, 6, 5}
Input: arr[] = {2, 7, 9, 5, 8, 7, 4}, k = 5
Output: 2
📝 Explanation
-
Find the window size → Count numbers ≤
k. -
Calculate "bad" elements (elements >
k) in the first window. -
Use Sliding Window:
-
Move the window right (remove old, add new).
-
Track the minimum "bad" count (which gives the min swaps).
-
-
Return minSwaps as the answer.
Takeaways
✅ We only check a window once → O(n) efficiency
✅ The bad count helps track unnecessary swaps
✅ Sliding one step at a time avoids nested loops (faster)
Step-by-Step Execution
Step 1: Calculate count (Window Size)
The window size is the count of elements ≤ k.
-
Elements ≤
3in{2, 1, 5, 6, 3}→ {2, 1, 3} -
Total count = 3
-
So, the window size is
3.
count = 3
Step 2: Count "bad" elements in the first window
A "bad" element is any number greater than k.
First window (size = 3) = {2, 1, 5}
-
2 → ✅ Good (≤ k)
-
1 → ✅ Good (≤ k)
-
5 → ❌ Bad (> k)
int bad = 0;for (int i = 0; i < count; i++) { if (arr[i] > k) bad++; }
🔹 bad = 1
Step 3: Slide the Window and Minimize "bad" elements
Now, we move the window right and update bad.
Iteration 1 (i = 3)
-
Old window: {2, 1, 5}
-
New window: {1, 5, 6}
-
Removed: 2 (✅ Good, no change in bad)
-
Added: 6 (❌ Bad, bad++)
bad = 2, but minSwaps = min(1, 2) = 1
Iteration 2 (i = 4)
-
Old window: {1, 5, 6}
-
New window: {5, 6, 3}
-
Removed: 1 (✅ Good, no change in bad)
-
Added: 3 (✅ Good, bad--)
bad = 1, so minSwaps = min(1, 1) = 1
Final Answer
After checking all windows, the minimum swaps needed = 1.
🔄 Code Flow Summary
| Step | Window | Removed | Added | Bad Count | minSwaps |
|---|---|---|---|---|---|
| Start | {2,1,5} | - | - | 1 | 1 |
| Move Right | {1,5,6} | 2 | 6 | 2 | 1 |
| Move Right | {5,6,3} | 1 | 3 | 1 | 1 |
Comments
Post a Comment