Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in Python

In binary arrays, we often need to find the optimal position to flip a 0 to 1 to create the longest possible sequence of consecutive 1s. This problem requires tracking sequences on both sides of each 0 to determine which replacement yields maximum benefit.

Given a binary array like [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1], we need to find which 0 should be replaced to get the longest continuous sequence of 1s. The answer is index 10, creating [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1].

Algorithm Approach

The solution uses a sliding window technique to track consecutive 1s on both sides of each 0 ?

  • Initialize counters for left and right sequences of 1s

  • For each 0 encountered, calculate the total sequence length if replaced

  • Track the index that gives maximum sequence length

  • Update counters as we move through the array

Implementation

def find_max_one_index(A):
    i = 0
    n = len(A)
    count_left = 0
    count_right = 0
    max_i = -1
    last_i = -1
    count_max = 0
    
    while i < n:
        if A[i] == 1:
            count_right += 1
        else:
            if last_i != -1:
                if count_right + count_left + 1 > count_max:
                    count_max = count_left + count_right + 1
                    max_i = last_i
            last_i = i
            count_left = count_right
            count_right = 0
        i += 1
    
    # Check the last zero position
    if last_i != -1:
        if count_left + count_right + 1 > count_max:
            count_max = count_left + count_right + 1
            max_i = last_i
    
    return max_i

# Test the function
binary_array = [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
result = find_max_one_index(binary_array)
print("Index to replace:", result)
print("Original array:", binary_array)

# Show the result after replacement
if result != -1:
    binary_array[result] = 1
    print("Modified array:", binary_array)
Index to replace: 10
Original array: [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
Modified array: [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1]

How It Works

The algorithm maintains four key variables ?

  • count_left: Number of consecutive 1s to the left of current 0

  • count_right: Number of consecutive 1s to the right of current 0

  • last_i: Index of the previously encountered 0

  • max_i: Index of 0 that gives maximum sequence when replaced

For each 0, it calculates count_left + count_right + 1 to determine the total sequence length if this 0 were replaced with 1.

Step-by-Step Trace

def find_max_one_index_debug(A):
    print(f"Array: {A}")
    print("Index | Value | count_left | count_right | max_sequence")
    print("-" * 55)
    
    i = 0
    n = len(A)
    count_left = 0
    count_right = 0
    max_i = -1
    last_i = -1
    count_max = 0
    
    while i < n:
        if A[i] == 1:
            count_right += 1
        else:
            if last_i != -1:
                sequence_length = count_right + count_left + 1
                print(f"{last_i:5} | {A[last_i]:5} | {count_left:10} | {count_right:11} | {sequence_length:12}")
                if sequence_length > count_max:
                    count_max = sequence_length
                    max_i = last_i
            last_i = i
            count_left = count_right
            count_right = 0
        i += 1
    
    # Check the last zero
    if last_i != -1:
        sequence_length = count_left + count_right + 1
        print(f"{last_i:5} | {A[last_i]:5} | {count_left:10} | {count_right:11} | {sequence_length:12}")
        if sequence_length > count_max:
            max_i = last_i
    
    print(f"\nBest index to replace: {max_i}")
    return max_i

binary_array = [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
find_max_one_index_debug(binary_array)
Array: [1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1]
Index | Value | count_left | count_right | max_sequence
-------------------------------------------------------
    2 |     0 |          2 |           0 |            3
    3 |     0 |          0 |           0 |            1
    5 |     0 |          1 |           0 |            2
   10 |     0 |          4 |           0 |            5
   10 |     0 |          4 |           2 |            7

Best index to replace: 10

Conclusion

This algorithm efficiently finds the optimal 0 to replace by tracking consecutive 1s around each 0 position. Replacing the 0 at index 10 creates the longest sequence of 7 consecutive 1s, making it the optimal choice for maximizing continuity in the binary array.

Updated on: 2026-03-25T09:41:40+05:30

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements