Minimum Number of K Consecutive Bit Flips — LeetCode 995 Python Solution

HardBit ManipulationQueueArrayPrefix SumSliding Window
Problem
#995
Reading time
3 min

The problem

You are given a binary array nums and an integer k. A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.

Example

Input
nums = [0,1,0], k = 1
Output
2
Explanation
Flip nums[0], then flip nums[2].

Python solution

Python
class Solution:
    def minKBitFlips(self, nums: List[int], k: int) -> int:
        n = len(nums)
        d = [0] * (n + 1)
        ans = s = 0
        for i, x in enumerate(nums):
            s += d[i]
            if s % 2 == x:
                if i + k > n:
                    return -1
                d[i] += 1
                d[i + k] -= 1
                s += 1
                ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 995. Minimum Number of K Consecutive Bit Flips 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 995. Minimum Number of K Consecutive Bit Flips?
LeetCode 995. Minimum Number of K Consecutive Bit Flips is rated Hard on LeetCode.
What is the time complexity of LeetCode 995. Minimum Number of K Consecutive Bit Flips?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 995. Minimum Number of K Consecutive Bit Flips?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 995. Minimum Number of K Consecutive Bit Flips cover?
LeetCode 995. Minimum Number of K Consecutive Bit Flips is tagged Bit Manipulation, Queue, 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