Longest sub string of 0’s in a Binary string

By | September 26, 2023

Given a string S containing 0’s and 1’s, the task is to find the length of longest continuous substring of 0’s from the given string.

Examples:

Input: S = 1111111
Output: 0
Explanation: There is no substring of 0's hence output is 0.

Approach: The given problem can be solved by simply iterating through the string.

Follow the steps below to solve the given problem:

  • Initialize a variable say currCount = 0, to keep the track of current length of the continuous substring of 0’s.
  • Initialize a variable say maxCount = 0, to store the maximum length of the continuous substring of 0’s.
  • Initialize a variable N to store the length of given string and i = 0 which acts as a iterator in the loop.
  • Iterate a loop till i <  and do the following operations:
    1. if S[i] == ‘0’ then increase currCount by one.
    2. else whenever we getting the element 1 we will re-assign maxCount to maximum of maxCount and currCount

Also we will make currCount = 0.

  • Now again check whether the currCount > 0 or currCount = 0
  • if currCount > 0, re-assign maxCount to maximum of maxCount and currCount .
  • After completing the above steps, print the value of maxCount as the result.

Below is the implementation of the above approach:

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

int getMaxLength(string S)
{
    // To store current count of substring
    int currCount = 0;

    // To store final maximum count of substring
    int maxCount = 0;

    // Variable to iterate over a string
    int i = 0;

    for (i = 0; i < S.length(); i++) {
        // if string element is 0
        // increase the currCount
        if (S[i] == '0')
            currCount++;

        // if string element is 1
        // re-assign maxCount and make currCount = 0
        else {
            maxCount = max(maxCount, currCount);
            currCount = 0;
        }
    }

    // for checking the last substring which is not followed
    // by 1 the currCount may greater than zero hence
    // re-assigning maxCount if currCount > 0
    if (currCount > 0)
        maxCount = max(maxCount, currCount);

    // Return final result
    return maxCount;
}

// Driver Code
int main()
{
    // input string
    string S("10010000");

    int maxLength = getMaxLength(S);

    cout << maxLength;
}

Output:

4

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