Leetcode 3191. Minimum Operations to Make Binary Array Elements Equal to One I
Table of Contents
Problem Informations
- Problem Index: 3191
- Problem Link: Minimum Operations to Make Binary Array Elements Equal to One I
- Topics: Array, Bit Manipulation, Queue, Sliding Window, Prefix Sum
Problem Description
You are given a binary array 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.
Example 1:
Input: nums = [0,1,1,1,0,0]
Output: 3
Explanation: We can do the following operations:
- Choose the elements at indices 0, 1 and 2. The resulting array is
nums = [1,0,0,1,0,0]
. - Choose the elements at indices 1, 2 and 3. The resulting array is
nums = [1,1,1,0,0,0]
. - Choose the elements at indices 3, 4 and 5. The resulting array is
nums = [1,1,1,1,1,1]
.
Example 2:
Input: nums = [0,1,1,1]
Output: -1
Explanation: It is impossible to make all elements equal to 1.
Constraints:
- $3 \leq \text{nums.length} \leq 10^5$
- $0 \leq \text{nums}[i] \leq 1$
Intuition
The problem revolves around minimizing the number of operations needed to turn a binary array into a uniform array of ones using the specific operation of flipping three consecutive elements. The challenge is to systematically apply this operation and decide when it is impossible to achieve the objective.
Approach
The approach involves iterating through the nums
array and performing the flipping operation as needed. The algorithm proceeds as follows:
Initialization: Start by getting the size of the
nums
array and initializing a counteroperations
to zero to keep track of the number of operations executed.Iterate Through Array: Traverse the
nums
array starting from the first element to the last.Check for Zero: For each element, check if it is zero. The presence of a zero indicates the necessity to perform a flipping operation to convert it into a one.
Perform Flip Operation:
- If a zero is encountered, increase the
operations
count. - Check if flipping can be performed: Ensure that there are at least two more elements after the current index (
i + 1
andi + 2
) in order to apply the flip operation on three consecutive elements. If not, return -1, indicating it’s impossible to make all elements one.
- If a zero is encountered, increase the
Flip Elements: If flipping is possible, change the next two consecutive elements from their current state:
nums[i + 1]
andnums[i + 2]
are flipped using the operation1 - nums[j]
.Output Result: Once the loop completes, return the total
operations
count as the result.
The algorithm leverages a straightforward greedy strategy, transforming zeros into ones as soon as they are encountered, using a local perspective to keep the operation minimal. This ensures all scenarios are covered while also detecting situations where it is impossible to convert the entire array to ones.
Code
C++
class Solution {
public:
int minOperations(vector<int>& nums) {
int n = nums.size(); // Get the size of the nums array
int operations = 0; // Initialize the number of operations needed to 0
for (int i = 0; i < n; i++) {
// Check if the current element is 0
if (nums[i] == 0) {
operations++; // Increment operation count for flipping
// Check if we have enough elements to flip
if (i + 2 >= n) return -1; // If not, return -1 indicating it's impossible
// Flip the next two consecutive elements
nums[i + 1] = 1 - nums[i + 1];
nums[i + 2] = 1 - nums[i + 2];
}
}
return operations; // Return the total number of operations required
}
};
Python
class Solution:
def minOperations(self, nums):
n = len(nums) # Get the size of the nums array
operations = 0 # Initialize the number of operations needed to 0
for i in range(n):
# Check if the current element is 0
if nums[i] == 0:
operations += 1 # Increment operation count for flipping
# Check if we have enough elements to flip
if i + 2 >= n:
return -1 # If not, return -1 indicating it's impossible
# Flip the next two consecutive elements
nums[i + 1] = 1 - nums[i + 1]
nums[i + 2] = 1 - nums[i + 2]
return operations # Return the total number of operations required
Complexity
Time complexity: $O(n)$
The algorithm processes each element in the array exactly once, making a decision based on the current element’s value and potentially flipping the next two elements if they exist. This results in a linear traversal of the array, leading to a time complexity of $O(n)$, where $n$ is the length of the array
nums
.Space complexity: $O(1)$
The algorithm operates in-place, only using a fixed amount of extra space for variables like
operations
and loop control variables. No additional data structures are used that grow with the input size, resulting in a constant space complexity of $O(1)$.
Disclaimer: All reference materials on this website are sourced from the internet and are intended for learning purposes only. If you believe any content infringes upon your rights, please contact me at csnote.cc@gmail.com, and I will remove the relevant content promptly.
Feedback Welcome: If you notice any errors or areas for improvement in the articles, I warmly welcome your feedback and corrections. Your input will help this blog provide better learning resources. This is an ongoing process of learning and improvement, and your suggestions are valuable to me. You can reach me at csnote.cc@gmail.com.