Minimum Adjacent Swaps for K Consecutive Ones - Problem
You are given an integer array nums comprising only 0's and 1's, and an integer k.
In one move, you can choose two adjacent indices and swap their values.
Return the minimum number of moves required so that nums has k consecutive 1's.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,0,1,0,1], k = 2
›
Output:
1
💡 Note:
We can make 2 consecutive 1's by swapping positions 1 and 2: [1,1,0,0,1]. This takes 1 swap.
Example 2 — Already Consecutive
$
Input:
nums = [1,0,1,0,1,0,1], k = 3
›
Output:
2
💡 Note:
The ones are at positions [0,2,4,6]. For any window of 3 ones, we need swaps to make them consecutive. The minimum cost is 2 swaps.
Example 3 — Larger Array
$
Input:
nums = [1,1,0,1,0,1,1,1,1], k = 4
›
Output:
2
💡 Note:
Optimal to use the last 4 ones at positions [5,6,7,8]. Need 2 swaps to make them consecutive.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is 0 or 1
- 1 ≤ k ≤ sum(nums)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code