Minimum Adjacent Swaps for K Consecutive Ones Problem
Description
LeetCode Problem 1703.
You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. 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.
Example 1:
Input: nums = [1,0,0,1,0,1], k = 2
Output: 1
Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
Example 2:
Input: nums = [1,0,0,0,0,0,1,1], k = 3
Output: 5
Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].
Example 3:
Input: nums = [1,1,0,1], k = 2
Output: 0
Explanation: nums already has 2 consecutive 1's.
Constraints:
1 <= nums.length <= 10^5nums[i]is0or1.1 <= k <= sum(nums)
Solution
Approach: Prefix Sums + Median
Collect the indices of the 1s into an array arr, and build its prefix sums s, where s[i] is the sum of the first i entries of arr.
For any k consecutive 1s (in arr), it is cheapest to gather them around their median. Let x = (k + 1) / 2 be the number of ones on the left side (median included) and y = k - x the number on the right.
Try every median index i with x - 1 <= i <= len(arr) - y - 1, and let j = arr[i] be its position in nums:
- The left
xones move to positionsj - x + 1 .. j. Their current sum isls = s[i + 1] - s[i + 1 - x], so the cost isa = (j + j - x + 1) * x / 2 - ls. - The right
yones move to positionsj + 1 .. j + y. Their current sum isrs = s[i + 1 + y] - s[i + 1], so the cost isb = rs - (j + 1 + j + y) * y / 2.
The answer is the smallest a + b over all medians.
Complexity: O(n) time and O(m) space, where n is the length of nums and m is the number of 1s.
from itertools import accumulate
from math import inf
class Solution:
def minMoves(self, nums: List[int], k: int) -> int:
arr = [i for i, x in enumerate(nums) if x]
s = list(accumulate(arr, initial=0))
ans = inf
x = (k + 1) // 2
y = k - x
for i in range(x - 1, len(arr) - y):
j = arr[i]
ls = s[i + 1] - s[i + 1 - x]
rs = s[i + 1 + y] - s[i + 1]
a = (j + j - x + 1) * x // 2 - ls
b = rs - (j + 1 + j + y) * y // 2
ans = min(ans, a + b)
return ans