![]() |
VOOZH | about |
Given a binary array arr[], Find minimum number of operations to convert all 0s to 1s. In one operation, we can select a subarray (window) of length k and flip all its bits. If it is impossible, return -1.
Examples:
Input: arr[] = [1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1], k = 2
Output: 4
Explanation: 4 operations are required to convert all 0s to 1s:
Flip arr[2...3], so arr[] becomes [1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1]
Flip arr[4...5], so arr[] becomes [1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1]
Flip arr[5...6], so arr[] becomes [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1]
Flip arr[6...7], so arr[] becomes [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]Input: arr[] = [0, 0, 1, 1, 1, 0, 0], k = 3
Output: -1
Explanation: It is impossible to convert all elements to 1s by performing any number of operations.
Table of Content
We scan the array from left to right, and whenever we see a 0, we flip the next k elements so that this 0 becomes 1. We keep doing this until we reach the last possible starting position. If at the end any 0 remains, it means it is impossible to make all elements 1; otherwise, the number of flips we made is the answer.
Working:
4
Instead of actually flipping k elements every time we see a 0, we use a prefix sum like trick. We maintain a flag that tells whether the current index is flipped or not, and an auxiliary flipped[] array to mark where a flip ends. This way, we avoid re-flipping the same subarray repeatedly.
Working:
4
Instead of keeping a whole auxiliary array to mark flip boundaries, we use a queue of size at most k to track active flips. The flag variable tells whether the current element is in a flipped state. When we encounter a 0, we start a new flip of size k and mark it in the queue; when we move past that window, we remove its effect from the flag.
Working:
4