Minimum Number of K Consecutive Bit Flips — LeetCode 995 Python Solution
- Problem
- #995
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.