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
Minimum Adjacent Swaps for K Consecutive Ones INPUT nums array: 1 i=0 0 i=1 1 i=2 0 i=3 1 i=4 Input Values: nums = [1,0,1,0,1] k = 2 Positions of 1s: [0, 2, 4] = 1 (target) = 0 ALGORITHM STEPS 1 Extract 1s positions pos = [0, 2, 4] 2 Sliding window k=2 Try windows of k ones 3 Find median position Move 1s toward median 4 Calculate min swaps Use prefix sums Window Analysis (k=2): Window [0,2]: median=0 cost = |2-1| = 1 swap Window [2,4]: median=2 cost = |4-3| = 1 swap min(1, 1) = 1 FINAL RESULT Before (1 swap needed): 1 0 1 0 1 swap After (k=2 consecutive): 1 1 0 0 1 k=2 consecutive! Output: 1 Minimum swaps = 1 [OK] Optimal solution Key Insight: Extract positions of all 1s, then use sliding window of size k. For each window, calculate the cost to move all 1s to consecutive positions around the median. The median minimizes total distance. Use prefix sums for O(n) calculation. Time: O(n), Space: O(n). TutorialsPoint - Minimum Adjacent Swaps for K Consecutive Ones | Optimal Solution
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