Minimum Adjacent Swaps for K Consecutive Ones - Problem
You're given a binary array nums containing only 0's and 1's, and an integer k. Your goal is to create a sequence of exactly k consecutive 1's using the minimum number of adjacent swaps.
In each move, you can swap two adjacent elements in the array. For example, if you have [0, 1, 0], you can swap positions 0 and 1 to get [1, 0, 0].
Challenge: Find the minimum number of swaps needed to group exactly k ones together consecutively anywhere in the array.
Example: Given nums = [1,0,0,1,0,1] and k = 2, you need at least 1 swap to get two consecutive 1's.
Input & Output
example_1.py โ Basic Case
$
Input:
[1,0,0,1,0,1]
k = 2
โบ
Output:
1
๐ก Note:
We have 1's at positions [0,3,5]. To get 2 consecutive 1's, the best strategy is to move the 1 from position 5 to position 4, requiring 1 swap: [1,0,0,1,1,0].
example_2.py โ Multiple Options
$
Input:
[1,0,0,0,0,0,1,1]
k = 3
โบ
Output:
5
๐ก Note:
We have 1's at positions [0,6,7]. To group all 3 together, we need to move them to consecutive positions. The optimal is to create [0,0,1,1,1,0,0,0], requiring 5 swaps total.
example_3.py โ Edge Case
$
Input:
[1,1,0,1]
k = 2
โบ
Output:
0
๐ก Note:
We already have 2 consecutive 1's at positions [0,1], so no swaps are needed.
Constraints
- 1 โค nums.length โค 105
- nums[i] is either 0 or 1
- 1 โค k โค sum(nums)
- k consecutive 1's must be possible (enough 1's exist in array)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Occupied Seats
Find all seats with people (1's) that need to be grouped together
2
Find Optimal Target Zone
Use sliding window to find the best consecutive seats to group people
3
Calculate Movement Cost
Use median principle: move people to positions around their median location
4
Execute Minimum Swaps
Perform the calculated minimum adjacent swaps to achieve the grouping
Key Takeaway
๐ฏ Key Insight: The median positioning principle minimizes total movement cost. By using a sliding window on the positions of 1's and calculating costs with prefix sums, we achieve an optimal O(n) solution that efficiently finds the minimum swaps needed to group k consecutive 1's.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code