Minimum Adjacent Swaps for K Consecutive Ones — LeetCode 1703 Python Solution

HardGreedyArrayPrefix SumSliding Window
Problem
#1703
Reading time
3 min

The problem

You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(m) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is rated Hard on LeetCode.
What is the time complexity of LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones cover?
LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones is tagged Greedy, Array, Prefix Sum and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview