LeetCode 3191, Medium. Topics: Array, Bit Manipulation, Queue, Sliding Window, Prefix Sum. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:
Problem
You are given a <span data-keyword=“binary-array”>binary array</span> nums.
You can do the following operation on the array any number of times (possibly zero):
- Choose any 3 consecutive elements from the array and flip all of them.
Flipping an element means changing its value from 0 to 1, and from 1 to 0.
Return the minimum number of operations required to make all elements in nums equal to 1. If it is impossible, return -1.
Examples
Constraints
- 3 <= nums.length <= 10^5
- 0 <= nums[i] <= 1
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026