Tutorialspoint
Problem
Solution
Submissions

K Consecutive Bit Flips

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Given a binary array nums and an integer k, you need to flip the values of k consecutive bits starting at various indices until all values in the array become 1. A flip operation changes 0s to 1s and 1s to 0s. Return the minimum number of k-bit flips required to make all values in nums equal to 1, or return -1 if it's not possible.

Example 1
  • Input: nums = [0,1,0], k = 2
  • Output: 2
  • Explanation:
    Step 1: Flip starting at index 0: [0,1,0] → [1,0,0]
    Step 2: Flip starting at index 1: [1,0,0] → [1,1,1]
    Step 3: All elements are now 1, so we needed 2 flips.
Example 2
  • Input: nums = [1,1,0], k = 2
  • Output: -1
  • Explanation:
    Step 1: If we flip starting at index 0: [1,1,0] → [0,0,0]
    Step 2: If we flip starting at index 1: [1,1,0] → [1,0,1]
    Step 3: In neither case can we make all elements 1 with flips of size 2.
    Step 4: Therefore, it's not possible to make all elements 1 with flips of size 2.
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • 1 ≤ k ≤ nums.length
  • nums[i] is either 0 or 1
  • Time Complexity: O(n)
  • Space Complexity: O(n) or O(1) with optimization
ArraysGoogleTech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Process the array from left to right.
  • If the current element is 0, you must flip k consecutive bits starting at this position.
  • Keep track of flips that have already been made and their effect on current position.
  • Use a greedy approach, flipping as early as possible.
  • Consider using a queue or array to track where flips have been made.
 Step 1: Create a flipTracker array to keep track of where we make flips.
 Step 2: Maintain a flipCount variable to know how many active flips affect the current position.
 Step 3: Process the array from left to right. At each index, check if the current bit (after accounting for previous flips) is 0.
 Step 4: If the current bit is 0, perform a flip operation by marking it in flipTracker and incrementing flipCount.
 Step 5: When moving to a new position, if we're past k positions from a flip, decrease flipCount since that flip no longer affects current positions.
 Step 6: If at any point we need to perform a flip but can't complete it (i+k > n), return -1.
 Step 7: Return the total number of flips needed.

Submitted Code :