1037. Minimum Number of K Consecutive Bit Flips
My accepted Python solution to LeetCode problem 1037, Minimum Number of K Consecutive Bit Flips, running in 255ms.
- Difficulty: Hard
- Python
- Runtime 255ms
- Memory 22.4MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 255ms, memory 22.4MB, accepted 2026-01-01.
class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
n = len(nums)
flips = 0
flip_queue = [] # Stores ending indices of active flips
for i in range(n):
# Remove flips that have ended
while flip_queue and flip_queue[0] <= i:
flip_queue.pop(0)
# Current effective value
current = nums[i] ^ (len(flip_queue) % 2)
if current == 0:
# Need to flip
if i + k > n:
return -1
flips += 1
flip_queue.append(i + k)
return flips