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: 0
💡 Note: The 1's at positions [2,4,6] can be made consecutive [1,1,1] in their current window with 0 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
Minimum Adjacent Swaps for K=3 Consecutive 1'sInput Array:10101011's at positions: [0, 2, 4, 6]Optimal Result:1113 consecutive 1's at positions [2,4,6]Minimum swaps needed: 0
Understanding the Visualization
1
Input
Array with scattered 1's and 0's, need k consecutive 1's
2
Find Positions
Extract positions of all 1's in the array
3
Calculate Swaps
Find optimal window requiring minimum adjacent swaps
Key Takeaway
🎯 Key Insight: Use sliding window over 1's positions with median-based cost calculation for optimal efficiency
Asked in
Google 25 Facebook 18 Amazon 15
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen