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

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).
Examples:

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 have discussed a solution for this problem in previous post. In this post two more methods to solve the problem are discussed.

Method 1(Using count of ones on both sides of zero): The idea is to count number of ones on both sides of each zero. The required index is the index of zero having maximum number of ones around it. Following variables are used in implementation:

  • leftCnt: To store count of ones on left side of current element zero under consideration.
  • rightCnt: To store count of ones on right side of current element zero under consideration.
  • maxIndex: Index of zero with maximum number of ones around it.
  • lastInd: Index of last zero element seen
  • maxCnt: Count of ones if zero at index maxInd is replaced by one.

Keep incrementing rightCnt until one is present in input array. Let next zero is present at index i. Check if this zero element is first zero element or not. It is first zero element if lastInd does not hold any valid index value. In that case update lastInd with i. Now the value of rightCnt is number of zeroes on left side of this zero. So leftCnt is equal to rightCnt and then again find value of rightCnt. If current zero element is not first zero, then number of ones around zero present at index lastInd is given by leftCnt + rightCnt. maxCnt will take value leftCnt + rightCnt + 1 and maxIndex = lastInd if this value is less than value currently held by maxCnt. Now rightCnt will become leftCnt for zero at index i and lastInd will be equal to i. Again find value of rightCnt, compare number of ones with maxcnt and update maxCnt and maxIndex accordingly. Repeat this procedure for each subsequent zero element of the array. Observe that lastInd stores the index of zero for which current leftCnt and rightCnt are calculated. The required index of zero to be replaced with one is stored in maxIndex.

Following is the implementation of the above algorithm.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find index of zero
// to be replaced by one to get longest
// continuous sequence of ones.
#include <bits/stdc++.h>
using namespace std;
  
// Returns index of 0 to be replaced
// with 1 to get longest continuous
// sequence of 1s. If there is no 0
// in array, then it returns -1.
int maxOnesIndex(bool arr[], int n)
{
    int i = 0;
  
    // To store count of ones on left
    // side of current element zero
    int leftCnt = 0;
  
    // To store count of ones on right
    // side of current element zero
    int rightCnt = 0;
  
    // Index of zero with maximum number
    // of ones around it.
    int maxIndex = -1;
  
    // Index of last zero element seen
    int lastInd = -1;
  
    // Count of ones if zero at index
    // maxInd is replaced by one.
    int maxCnt = 0;
  
    while (i < n) {
  
        // Keep incrementing count until
        // current element is 1.
        if (arr[i]) {
            rightCnt++;
        }
  
        else {
  
            // If current zero element
            // is not first zero element,
            // then count number of ones
            // obtained by replacing zero at
            // index lastInd. Update maxCnt
            // and maxIndex if required.
            if (lastInd != -1) {
                if (rightCnt + leftCnt + 1 > maxCnt) {
                    maxCnt = leftCnt + rightCnt + 1;
                    maxIndex = lastInd;
                }
            }
            lastInd = i;
            leftCnt = rightCnt;
            rightCnt = 0;
        }
  
        i++;
    }
  
    // Find number of ones in continuous
    // sequence when last zero element is
    // replaced by one.
    if (lastInd != -1) {
        if (leftCnt + rightCnt + 1 > maxCnt) {
            maxCnt = leftCnt + rightCnt + 1;
            maxIndex = lastInd;
        }
    }
  
    return maxIndex;
}
  
// Driver function
int main()
{
    bool arr[] = { 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 };
    // bool arr[] = {1, 1, 1, 1, 0};
  
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Index of 0 to be replaced is "
        << maxOnesIndex(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find index of zero 
// to be replaced by one to get longest 
// continuous sequence of ones.
  
class GFG {
  
// Returns index of 0 to be replaced 
// with 1 to get longest continuous 
// sequence of 1s. If there is no 0 
// in array, then it returns -1. 
    static int maxOnesIndex(boolean arr[], int n) {
        int i = 0;
  
        // To store count of ones on left 
        // side of current element zero 
        int leftCnt = 0;
  
        // To store count of ones on right 
        // side of current element zero 
        int rightCnt = 0;
  
        // Index of zero with maximum number 
        // of ones around it. 
        int maxIndex = -1;
  
        // Index of last zero element seen 
        int lastInd = -1;
  
        // Count of ones if zero at index 
        // maxInd is replaced by one. 
        int maxCnt = 0;
  
        while (i < n) {
  
            // Keep incrementing count until 
            // current element is 1. 
            if (arr[i]) {
                rightCnt++;
            } else {
  
                // If current zero element 
                // is not first zero element, 
                // then count number of ones 
                // obtained by replacing zero at 
                // index lastInd. Update maxCnt 
                // and maxIndex if required. 
                if (lastInd != -1) {
                    if (rightCnt + leftCnt + 1 > maxCnt) {
                        maxCnt = leftCnt + rightCnt + 1;
                        maxIndex = lastInd;
                    }
                }
                lastInd = i;
                leftCnt = rightCnt;
                rightCnt = 0;
            }
  
            i++;
        }
  
        // Find number of ones in continuous 
        // sequence when last zero element is 
        // replaced by one. 
        if (lastInd != -1) {
            if (leftCnt + rightCnt + 1 > maxCnt) {
                maxCnt = leftCnt + rightCnt + 1;
                maxIndex = lastInd;
            }
        }
  
        return maxIndex;
    }
  
    // Driver function 
    public static void main(String[] args) {
        boolean arr[] = {true, true, false, false, true,
            false, true, true, true, false, true, true, true,};
  
        int n = arr.length;
        System.out.println("Index of 0 to be replaced is "
                + maxOnesIndex(arr, n));
    }
}
//This code contribute by Shikha Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find index of zero 
# to be replaced by one to get longest 
# continuous sequence of ones. 
  
# Returns index of 0 to be replaced 
# with 1 to get longest continuous 
# sequence of 1s. If there is no 0 
# in array, then it returns -1. 
def maxOnesIndex(arr, n): 
  
    i = 0
  
    # To store count of ones on left 
    # side of current element zero 
    leftCnt = 0
  
    # To store count of ones on right 
    # side of current element zero 
    rightCnt = 0
  
    # Index of zero with maximum number 
    # of ones around it. 
    maxIndex = -1
  
    # Index of last zero element seen 
    lastInd = -1
  
    # Count of ones if zero at index 
    # maxInd is replaced by one. 
    maxCnt = 0
  
    while i < n: 
  
        # Keep incrementing count until 
        # current element is 1. 
        if arr[i] == 1
            rightCnt += 1
  
        else:
            # If current zero element 
            # is not first zero element, 
            # then count number of ones 
            # obtained by replacing zero at 
            # index lastInd. Update maxCnt 
            # and maxIndex if required. 
            if lastInd != -1
                if rightCnt + leftCnt + 1 > maxCnt: 
                    maxCnt = leftCnt + rightCnt + 1
                    maxIndex = lastInd 
                  
            lastInd =
            leftCnt = rightCnt 
            rightCnt = 0
          
        i += 1
  
    # Find number of ones in continuous 
    # sequence when last zero element is 
    # replaced by one. 
    if lastInd != -1
        if leftCnt + rightCnt + 1 > maxCnt: 
            maxCnt = leftCnt + rightCnt + 1
            maxIndex = lastInd 
          
    return maxIndex 
  
# Driver code 
if __name__ == "__main__":
  
    arr = [1, 1, 0, 0, 1, 0, 1,
              1, 1, 0, 1, 1, 1
      
    n = len(arr) 
    print("Index of 0 to be replaced is",
                    maxOnesIndex(arr, n)) 
  
# This code is contributed 
# by Rituraj Jain 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find index of zero 
// to be replaced by one to get longest 
// continuous sequence of ones. 
  
  
using System;
  
public class GFG{
  
// Returns index of 0 to be replaced 
// with 1 to get longest continuous 
// sequence of 1s. If there is no 0 
// in array, then it returns -1. 
    static int maxOnesIndex(bool []arr, int n) { 
        int i = 0; 
  
        // To store count of ones on left 
        // side of current element zero 
        int leftCnt = 0; 
  
        // To store count of ones on right 
        // side of current element zero 
        int rightCnt = 0; 
  
        // Index of zero with maximum number 
        // of ones around it. 
        int maxIndex = -1; 
  
        // Index of last zero element seen 
        int lastInd = -1; 
  
        // Count of ones if zero at index 
        // maxInd is replaced by one. 
        int maxCnt = 0; 
  
        while (i < n) { 
  
            // Keep incrementing count until 
            // current element is 1. 
            if (arr[i]) { 
                rightCnt++; 
            } else
  
                // If current zero element 
                // is not first zero element, 
                // then count number of ones 
                // obtained by replacing zero at 
                // index lastInd. Update maxCnt 
                // and maxIndex if required. 
                if (lastInd != -1) { 
                    if (rightCnt + leftCnt + 1 > maxCnt) { 
                        maxCnt = leftCnt + rightCnt + 1; 
                        maxIndex = lastInd; 
                    
                
                lastInd = i; 
                leftCnt = rightCnt; 
                rightCnt = 0; 
            
  
            i++; 
        
  
        // Find number of ones in continuous 
        // sequence when last zero element is 
        // replaced by one. 
        if (lastInd != -1) { 
            if (leftCnt + rightCnt + 1 > maxCnt) { 
                maxCnt = leftCnt + rightCnt + 1; 
                maxIndex = lastInd; 
            
        
  
        return maxIndex; 
    
  
    // Driver function 
    static public void Main (){
        bool []arr = {true, true, false, false, true
            false, true, true, true, false, true, true, true,}; 
  
        int n = arr.Length; 
        Console.WriteLine("Index of 0 to be replaced is "
                + maxOnesIndex(arr, n)); 
    
//This code contribute by ajit 

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find index of zero
// to be replaced by one to get longest
// continuous sequence of ones.
  
// Returns index of 0 to be replaced
// with 1 to get longest continuous
// sequence of 1s. If there is no 0
// in array, then it returns -1.
function maxOnesIndex($arr, $n)
{
    $i = 0;
  
    // To store count of ones on left
    // side of current element zero
    $leftCnt = 0;
  
    // To store count of ones on right
    // side of current element zero
    $rightCnt = 0;
  
    // Index of zero with maximum number
    // of ones around it.
    $maxIndex = -1;
  
    // Index of last zero element seen
    $lastInd = -1;
  
    // Count of ones if zero at index
    // maxInd is replaced by one.
    $maxCnt = 0;
  
    while ($i < $n
    {
  
        // Keep incrementing count until
        // current element is 1.
        if ($arr[$i]) 
        {
            $rightCnt++;
        }
  
        else
        {
  
            // If current zero element
            // is not first zero element,
            // then count number of ones
            // obtained by replacing zero at
            // index lastInd. Update maxCnt
            // and maxIndex if required.
            if ($lastInd != -1) 
            {
                if ($rightCnt + $leftCnt + 1 > $maxCnt
                {
                    $maxCnt = $leftCnt + $rightCnt + 1;
                    $maxIndex = $lastInd;
                }
            }
            $lastInd = $i;
            $leftCnt = $rightCnt;
            $rightCnt = 0;
        }
  
        $i++;
    }
  
    // Find number of ones in continuous
    // sequence when last zero element is
    // replaced by one.
    if ($lastInd != -1) 
    {
        if ($leftCnt + $rightCnt + 1 > $maxCnt)
        {
            $maxCnt = $leftCnt + $rightCnt + 1;
            $maxIndex = $lastInd;
        }
    }
  
    return $maxIndex;
}
  
// Driver Code
$arr = array(1, 1, 0, 0, 1, 0, 
            1, 1, 1, 0, 1, 1, 1);
// bool arr[] = {1, 1, 1, 1, 0};
  
$n = sizeof($arr);
echo "Index of 0 to be replaced is "
              maxOnesIndex($arr, $n);
  
// This code is contributed 
// by Akanksha Rai
?>

chevron_right



Output:

Index of 0 to be replaced is 9

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

Method 2(Using sliding window): A sliding window is used to find number of ones in longest continuous sequence obtained by replacing a zero. The idea is to keep incrementing ending point of sliding window until one is present in input array. When a zero is found, check if it is first zero element or not. If it is first zero element then the sliding window is expanded further. If it is not, then find the length of sliding window. This length is number of ones obtained by replacing the zero element present in sliding window. Note that this length gives number of ones obtained by replacing previous zero element and not current zero element. For current zero element, the starting point of sliding window is index next to the index of previous zero element.

Following is the implementation of the above algorithm.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find index of zero
// to be replaced by one to get longest
// continuous sequence of ones.
#include <bits/stdc++.h>
using namespace std;
  
// Returns index of 0 to be replaced
// with 1 to get longest continuous
// sequence of 1s.  If there is no 0
// in array, then it returns -1.
int maxOnesIndex(bool arr[], int n)
{
  
    // To store starting point of
    // sliding window.
    int start = 0;
  
    // To store ending point of
    // sliding window.
    int end = 0;
  
    // Index of zero with maximum number
    // of ones around it.
    int maxIndex = -1;
  
    // Index of last zero element seen
    int lastInd = -1;
  
    // Count of ones if zero at index
    // maxInd is replaced by one.
    int maxCnt = 0;
  
    while (end < n) {
  
        // Keep increasing ending point
        // of sliding window until one is
        // present in input array.
        while (end < n && arr[end]) {
            end++;
        }
  
        // If this is not first zero element
        // then number of ones obtained by
        // replacing zero at lastInd is
        // equal to length of window.
        // Compare this with maximum number
        // of ones in a previous window so far.
        if (maxCnt < end - start && lastInd != -1) {
            maxCnt = end - start;
            maxIndex = lastInd;
        }
  
        // The new starting point of next window
        // is from index position next to last
        // zero which is stored in lastInd.
        start = lastInd + 1;
        lastInd = end;
        end++;
    }
  
    // For the case when only one zero is
    // present in input array and is at
    // last position.
    if (maxCnt < end - start && lastInd != -1) {
        maxCnt = end - start;
        maxIndex = lastInd;
    }
  
    return maxIndex;
}
  
// Driver function
int main()
{
    bool arr[] = { 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1 };
    // bool arr[] = {1, 1, 1, 1, 0};
  
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Index of 0 to be replaced is "
         << maxOnesIndex(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find index of zero 
// to be replaced by one to get longest 
// continuous sequence of ones.
  
public class GFG {
  
// Returns index of 0 to be replaced 
// with 1 to get longest continuous 
// sequence of 1s. If there is no 0 
// in array, then it returns -1. 
    static int maxOnesIndex(boolean arr[], int n) {
  
        // To store starting point of 
        // sliding window. 
        int start = 0;
  
        // To store ending point of 
        // sliding window. 
        int end = 0;
  
        // Index of zero with maximum number 
        // of ones around it. 
        int maxIndex = -1;
  
        // Index of last zero element seen 
        int lastInd = -1;
  
        // Count of ones if zero at index 
        // maxInd is replaced by one. 
        int maxCnt = 0;
  
        while (end < n) {
  
            // Keep increasing ending point 
            // of sliding window until one is 
            // present in input array. 
            while (end < n && arr[end]) {
                end++;
            }
  
            // If this is not first zero element 
            // then number of ones obtained by 
            // replacing zero at lastInd is 
            // equal to length of window. 
            // Compare this with maximum number 
            // of ones in a previous window so far. 
            if (maxCnt < end - start && lastInd != -1) {
                maxCnt = end - start;
                maxIndex = lastInd;
            }
  
            // The new starting point of next window 
            // is from index position next to last 
            // zero which is stored in lastInd. 
            start = lastInd + 1;
            lastInd = end;
            end++;
        }
  
        // For the case when only one zero is 
        // present in input array and is at 
        // last position. 
        if (maxCnt < end - start && lastInd != -1) {
            maxCnt = end - start;
            maxIndex = lastInd;
        }
  
        return maxIndex;
    }
  
    // Driver function 
    static public void main(String[] args) {
        boolean arr[] = {true, true, false, false, true,
            false, true, true, true, false, true, true, true,};
  
        // bool arr[] = {1, 1, 1, 1, 0}; 
        int n = arr.length;
        System.out.println("Index of 0 to be replaced is "
                + maxOnesIndex(arr, n));
    }
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find index of zero
# to be replaced by one to get longest
# continuous sequence of ones.
  
# Returns index of 0 to be replaced
# with 1 to get longest continuous
# sequence of 1s. If there is no 0
# in array, then it returns -1.
def maxOnesIndex(arr, n):
  
    # To store starting point of
    # sliding window.
    start = 0
  
    # To store ending point of
    # sliding window.
    end = 0
  
    # Index of zero with maximum 
    # number of ones around it.
    maxIndex = -1
  
    # Index of last zero element seen
    lastInd = -1
  
    # Count of ones if zero at index
    # maxInd is replaced by one.
    maxCnt = 0
  
    while (end < n) :
  
        # Keep increasing ending point
        # of sliding window until one is
        # present in input array.
        while (end < n and arr[end]) :
            end += 1
          
        # If this is not first zero element
        # then number of ones obtained by
        # replacing zero at lastInd is
        # equal to length of window.
        #Compare this with maximum number
        # of ones in a previous window so far.
        if (maxCnt < end - start and lastInd != -1) :
            maxCnt = end - start
            maxIndex = lastInd
          
  
        # The new starting point of next window
        # is from index position next to last
        # zero which is stored in lastInd.
        start = lastInd + 1
        lastInd = end
        end += 1
      
    # For the case when only one zero is
    # present in input array and is at
    # last position.
    if (maxCnt < end - start and lastInd != -1) :
        maxCnt = end - start
        maxIndex = lastInd
  
    return maxIndex
  
# Driver Code
if __name__ == "__main__":
  
    arr = [1, 1, 0, 0, 1, 0, 1
              1, 1, 0, 1, 1, 1 ]
    # arr= [1, 1, 1, 1, 0]
  
    n = len(arr)
    print ("Index of 0 to be replaced is ",
                      maxOnesIndex(arr, n))
  
# This code is contributed by ChitraNayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

using System;
  
// c# program to find index of zero  
// to be replaced by one to get longest  
// continuous sequence of ones. 
  
public class GFG
{
  
// Returns index of 0 to be replaced  
// with 1 to get longest continuous  
// sequence of 1s. If there is no 0  
// in array, then it returns -1.  
    public static int maxOnesIndex(bool[] arr, int n)
    {
  
        // To store starting point of  
        // sliding window.  
        int start = 0;
  
        // To store ending point of  
        // sliding window.  
        int end = 0;
  
        // Index of zero with maximum number  
        // of ones around it.  
        int maxIndex = -1;
  
        // Index of last zero element seen  
        int lastInd = -1;
  
        // Count of ones if zero at index  
        // maxInd is replaced by one.  
        int maxCnt = 0;
  
        while (end < n)
        {
  
            // Keep increasing ending point  
            // of sliding window until one is  
            // present in input array.  
            while (end < n && arr[end])
            {
                end++;
            }
  
            // If this is not first zero element  
            // then number of ones obtained by  
            // replacing zero at lastInd is  
            // equal to length of window.  
            // Compare this with maximum number  
            // of ones in a previous window so far.  
            if (maxCnt < end - start && lastInd != -1)
            {
                maxCnt = end - start;
                maxIndex = lastInd;
            }
  
            // The new starting point of next window  
            // is from index position next to last  
            // zero which is stored in lastInd.  
            start = lastInd + 1;
            lastInd = end;
            end++;
        }
  
        // For the case when only one zero is  
        // present in input array and is at  
        // last position.  
        if (maxCnt < end - start && lastInd != -1)
        {
            maxCnt = end - start;
            maxIndex = lastInd;
        }
  
        return maxIndex;
    }
  
        // Driver function  
    public static void Main(string[] args)
    {
        bool[] arr = new bool[] {true, true, false, false, true, false, true, true, true, false, true, true, true};
  
        // bool arr[] = {1, 1, 1, 1, 0};  
        int n = arr.Length;
        Console.WriteLine("Index of 0 to be replaced is " + maxOnesIndex(arr, n));
    }
}
  
// This code is contributed by Shrikant13

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find index of zero
// to be replaced by one to get longest
// continuous sequence of ones.
  
// Returns index of 0 to be replaced
// with 1 to get longest continuous
// sequence of 1s. If there is no 0
// in array, then it returns -1.
function maxOnesIndex($arr, $n)
{
  
    // To store starting point of
    // sliding window.
    $start = 0;
  
    // To store ending point of
    // sliding window.
    $end = 0;
  
    // Index of zero with maximum 
    // number of ones around it.
    $maxIndex = -1;
  
    // Index of last zero element seen
    $lastInd = -1;
  
    // Count of ones if zero at index
    // maxInd is replaced by one.
    $maxCnt = 0;
  
    while ($end < $n
    {
  
        // Keep increasing ending point
        // of sliding window until one is
        // present in input array.
        while ($end < $n && $arr[$end]) 
        {
            $end++;
        }
  
        // If this is not first zero element
        // then number of ones obtained by
        // replacing zero at lastInd is
        // equal to length of window.
        // Compare this with maximum number
        // of ones in a previous window so far.
        if ($maxCnt < $end - $start && 
                      $lastInd != -1) 
        {
            $maxCnt = $end - $start;
            $maxIndex = $lastInd;
        }
  
        // The new starting point of next window
        // is from index position next to last
        // zero which is stored in lastInd.
        $start = $lastInd + 1;
        $lastInd = $end;
        $end++;
    }
  
    // For the case when only one zero is
    // present in input array and is at
    // last position.
    if ($maxCnt < $end - $start && $lastInd != -1)
    {
        $maxCnt = $end - $start;
        $maxIndex = $lastInd;
    }
  
    return $maxIndex;
}
  
// Driver Code
$arr = array( 1, 1, 0, 0, 1, 0, 1, 
              1, 1, 0, 1, 1, 1 );
// bool arr[] = {1, 1, 1, 1, 0};
  
$n = sizeof($arr);
echo "Index of 0 to be replaced is ",
maxOnesIndex($arr, $n);
  
// This code is contributed 
// by Sach_Code
?>

chevron_right



Output:

Index of 0 to be replaced is 9

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



My Personal Notes arrow_drop_up

A Programmer and A Machine learning Enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.