VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-index-0-replaced-1-get-longest-continuous-sequence-1s-binary-array/

⇱ Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array

Last Updated : 24 Jun, 2022

Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1). 

Example: 

Input: 
 arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}
Output:
 Index 9
Assuming array index starts from 0, replacing 0 with 1 at index 9 causes
the maximum continuous sequence of 1s.

Input: 
 arr[] = {1, 1, 1, 1, 0}
Output:
 Index 4

We strongly recommend to minimize the browser and try this yourself first.

A Simple Solution is to traverse the array, for every 0, count the number of 1s on both sides of it. Keep track of maximum count for any 0. Finally return index of the 0 with maximum number of 1s around it. The time complexity of this solution is O(n2).

Using an Efficient Solution, the problem can solved in O(n) time. The idea is to keep track of three indexes, current index (curr), previous zero index (prev_zero) and previous to previous zero index (prev_prev_zero). Traverse the array, if current element is 0, calculate the difference between curr and prev_prev_zero (This difference minus one is the number of 1s around the prev_zero). If the difference between curr and prev_prev_zero is more than maximum so far, then update the maximum. Finally return index of the prev_zero with maximum difference.

Following are the implementations of the above algorithm. 


Output
Index of 0 to be replaced is 9

Time Complexity: O(n) 
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: