Program to find length of longest set of 1s by flipping k bits in Python

In this problem, we have a binary list containing only 0s and 1s, and we can flip at most k zeros to ones. Our goal is to find the length of the longest contiguous subarray that contains all 1s after performing these flips.

For example, if the input is nums = [0, 1, 1, 0, 0, 1, 1] and k = 2, we can flip the two middle 0s to get [0, 1, 1, 1, 1, 1, 1], resulting in a longest sequence of 6 consecutive 1s.

Algorithm Approach

We'll use the sliding window technique to solve this problem efficiently ?

  • zeros := count of zeros in current window
  • ans := maximum window size found so far
  • j := left pointer of the sliding window
  • For each index i (right pointer), expand the window
  • If zeros exceed k, shrink the window from left
  • Update the maximum window size

Implementation

class Solution:
    def solve(self, nums, k):
        zeros = 0
        ans = 0
        j = 0
        
        for i, n in enumerate(nums):
            # Expand window: count zeros
            zeros += n == 0
            
            # Shrink window if too many zeros
            while zeros > k:
                zeros -= nums[j] == 0
                j += 1
            
            # Update maximum window size
            if i - j + 1 > ans:
                ans = i - j + 1
                
        return ans

# Test the solution
ob = Solution()
nums = [0, 1, 1, 0, 0, 1, 1]
k = 2
print(f"Input: {nums}, k = {k}")
print(f"Output: {ob.solve(nums, k)}")
Input: [0, 1, 1, 0, 0, 1, 1], k = 2
Output: 6

How It Works

Let's trace through the example step by step ?

def solve_with_trace(nums, k):
    zeros = 0
    ans = 0
    j = 0
    
    print(f"Array: {nums}, k = {k}")
    print("Step | Window | Zeros | Max Length")
    print("-" * 35)
    
    for i, n in enumerate(nums):
        zeros += n == 0
        
        while zeros > k:
            zeros -= nums[j] == 0
            j += 1
        
        window_size = i - j + 1
        if window_size > ans:
            ans = window_size
            
        print(f" {i+1:2d}  | [{j}:{i+1}]  |   {zeros}   |     {ans}")
    
    return ans

nums = [0, 1, 1, 0, 0, 1, 1]
k = 2
result = solve_with_trace(nums, k)
print(f"\nFinal answer: {result}")
Array: [0, 1, 1, 0, 0, 1, 1], k = 2
Step | Window | Zeros | Max Length
-----------------------------------
  1  | [0:1]  |   1   |     1
  2  | [0:2]  |   1   |     2
  3  | [0:3]  |   1   |     3
  4  | [0:4]  |   2   |     4
  5  | [0:5]  |   3   |     4
  6  | [2:6]  |   2   |     5
  7  | [2:7]  |   2   |     6

Final answer: 6

Key Points

  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(1) as we only use a few variables
  • The sliding window expands by moving the right pointer and shrinks by moving the left pointer
  • We maintain at most k zeros in our current window

Alternative Test Cases

ob = Solution()

# Test case 1: All zeros
nums1 = [0, 0, 0, 0]
k1 = 2
print(f"Test 1: {nums1}, k={k1} ? {ob.solve(nums1, k1)}")

# Test case 2: All ones
nums2 = [1, 1, 1, 1]
k2 = 1
print(f"Test 2: {nums2}, k={k2} ? {ob.solve(nums2, k2)}")

# Test case 3: No flips allowed
nums3 = [1, 0, 1, 1, 0]
k3 = 0
print(f"Test 3: {nums3}, k={k3} ? {ob.solve(nums3, k3)}")
Test 1: [0, 0, 0, 0], k=2 ? 2
Test 2: [1, 1, 1, 1], k=1 ? 4
Test 3: [1, 0, 1, 1, 0], k=0 ? 2

Conclusion

The sliding window technique efficiently solves this problem in linear time by maintaining a window with at most k zeros. This approach avoids checking all possible subarrays, making it optimal for finding the longest sequence of 1s after flipping k bits.

Updated on: 2026-03-25T12:36:45+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements