Given a binary array, find the index of 0 to be replaced with 1 to get the maximum length sequence of continuous ones.

For example, consider the array { 0, 0, 1, 0, 1, 1, 1, 0, 1, 1 }. We need to replace index 7 to get the continuous sequence of length 6 containing all 1’s.

Practice this problem

 
We can efficiently solve this problem in linear time and constant space. The idea is to traverse the given array and maintain an index of the previous zero encountered. We can then easily find out the total number of 1’s between the current zero and the last zero for each subsequent zeros. For each element, check if the maximum sequence of continuous 1’s ending at that element (including the last zero, which is now replaced by 1) exceeds the maximum sequence found so far. If yes, update the maximum sequence to the current sequence length and index of optimal zero and index the last zero encountered.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Index to be replaced is 7

Java


Download  Run Code

Output:

Index to be replaced is 7

Python


Download  Run Code

Output:

Index to be replaced is 7

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the given sequence.

 
We have discussed two more approaches to solve this problem:

Find maximum length sequence of continuous ones

Find maximum length sequence of continuous ones (Using Sliding Window)