Skip to content
Related Articles

Related Articles

Longest Substring of 1’s after removing one character
  • Difficulty Level : Medium
  • Last Updated : 22 Dec, 2020

Given a binary string S of length N, the task is to find the longest substring consisting of ‘1’s only present in the string after deleting a character from the string.

Examples:

Input: S = “1101”
Output: 3
Explanation: 
Removing S[0], S modifies to “101”. Longest possible substring of ‘1’s is 1.
Removing S[1], S modifies to “101”. Longest possible substring of ‘1’s is 1.
Remoing S[2], S modifies to “111”. Longest possible substring of ‘1’s is 3.
Removing S[3], S modifies to “110”. Longest possible substring of ‘1’s is 2.
Therefore, longest substring of ‘1’s that can be obtained is 3.

Input: S = “011101101”
Output: 5

Method 1: The idea is to traverse the string and search for ‘0’s in the given string. For every character which is found to be ‘0’, add the length of its adjacent substrings of ‘1’. Print the maximum of all such lengths obtained.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
    // Add '0' at the end
    s += '0';
 
    // Iterator to traverse the string
    int i;
 
    // Stores maximum length
    // of required substring
    int res = 0;
 
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
 
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
 
    // Counts number of '0's
    int numberOfZeros = 0;
 
    // Traverse the string S
    for (i = 0; i < s.length(); i++) {
 
        // If current character is '1'
        if (s[i] == '1') {
 
            // Increase curr_one by one
            curr_one += 1;
        }
 
        // Otherwise
        else {
 
            // Increment numberofZeros by one
            numberOfZeros += 1;
 
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding substrings of '1'
            prev_one += curr_one;
 
            // Store maximum size in res
            res = max(res, prev_one);
 
            // Assign curr_one to prev_one
            prev_one = curr_one;
 
            // Reset curr_one
            curr_one = 0;
        }
    }
 
    // If string contains only one '0'
    if (numberOfZeros == 1) {
        res -= 1;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
    string S = "1101";
    cout << longestSubarray(S);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.Arrays;
  
class GFG{
      
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
     
    // Add '0' at the end
    s += '0';
     
    // Iterator to traverse the string
    int i;
     
    // Stores maximum length
    // of required substring
    int res = 0;
     
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
  
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
  
    // Counts number of '0's
    int numberOfZeros = 0;
  
    // Traverse the string S
    for(i = 0; i < s.length(); i++)
    {
         
        // If current character is '1'
        if (s.charAt(i) == '1')
        {
             
            // Increase curr_one by one
            curr_one += 1;
        }
  
        // Otherwise
        else
        {
             
            // Increment numberofZeros by one
            numberOfZeros += 1;
  
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding
            // substrings of '1'
            prev_one += curr_one;
  
            // Store maximum size in res
            res = Math.max(res, prev_one);
  
            // Assign curr_one to prev_one
            prev_one = curr_one;
  
            // Reset curr_one
            curr_one = 0;
        }
    }
  
    // If string contains only one '0'
    if (numberOfZeros == 1)
    {
        res -= 1;
    }
     
    // Return the answer
    return res;
}
  
// Driver Code
public static void main (String[] args)
{
    String S = "1101";
     
    System.out.println(longestSubarray(S));
}
}
 
// This code is contributed by code_hunt

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
     
    # Add '0' at the end
    s += '0'
 
    # Iterator to traverse the string
    i = 0
 
    # Stores maximum length
    # of required substring
    res = 0
 
    # Stores length of substring of '1'
    # preceding the current character
    prev_one = 0
 
    # Stores length of substring of '1'
    # succeeding the current character
    curr_one = 0
 
    # Counts number of '0's
    numberOfZeros = 0
 
    # Traverse the string S
    for i in range(len(s)):
         
        # If current character is '1'
        if (s[i] == '1'):
             
            # Increase curr_one by one
            curr_one += 1
 
        # Otherwise
        else:
             
            # Increment numberofZeros by one
            numberOfZeros += 1
 
            # Count length of substring
            # obtained y concatenating
            # preceding and succeeding
            # substrings of '1'
            prev_one += curr_one
 
            # Store maximum size in res
            res = max(res, prev_one)
 
            # Assign curr_one to prev_one
            prev_one = curr_one
 
            # Reset curr_one
            curr_one = 0
 
    # If string contains only one '0'
    if (numberOfZeros == 1):
        res -= 1
 
    # Return the answer
    return res
 
# Driver Code
if __name__ == '__main__':
     
    S = "1101"
     
    print(longestSubarray(S))
 
# This code is contributed by ipg2016107

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG
{
      
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
     
    // Add '0' at the end
    s += '0';
     
    // Iterator to traverse the string
    int i;
     
    // Stores maximum length
    // of required substring
    int res = 0;
     
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
  
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
  
    // Counts number of '0's
    int numberOfZeros = 0;
  
    // Traverse the string S
    for(i = 0; i < s.Length; i++)
    {
         
        // If current character is '1'
        if (s[i] == '1')
        {
             
            // Increase curr_one by one
            curr_one += 1;
        }
  
        // Otherwise
        else
        {
             
            // Increment numberofZeros by one
            numberOfZeros += 1;
  
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding
            // substrings of '1'
            prev_one += curr_one;
  
            // Store maximum size in res
            res = Math.Max(res, prev_one);
  
            // Assign curr_one to prev_one
            prev_one = curr_one;
  
            // Reset curr_one
            curr_one = 0;
        }
    }
  
    // If string contains only one '0'
    if (numberOfZeros == 1)
    {
        res -= 1;
    }
     
    // Return the answer
    return res;
}
  
// Driver Code
public static void Main(String[] args)
{
    String S = "1101";
     
    Console.WriteLine(longestSubarray(S));
}
}
 
 
// This code is contributed by shikhasingrajput

chevron_right


Output: 

3

 

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

Method 2: Alternate approach to solve the problem is to use sliding window technique for finding the maximum length of substring containing only ‘1’s after deleting a single character. Follow the steps below to solve the problem:

  • Initialize 3 integer variables i, j, with 0 and k with 1
  • Iterate over the characters of the string S.
    • For every character traveresed, check if it is ‘0’ or not. If found to be true, decrement k by 1.
    • If k < 0 and character at ith index is ‘0’, increment k and i by one
    • Increment j by one.
  • Finally, print the length j – i – 1 after complete traversal of the string.

Below is the implementation of the above approach: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.size(); ++j) {
 
        // If current character is '0'
        if (s[j] == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
int main()
{
    string S = "011101101";
    cout << longestSubarray(S);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
 
import java.util.*;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.length(); ++j)
    {
 
        // If current character is '0'
        if (s.charAt(j) == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s.charAt(i++) == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "011101101";
    System.out.print(longestSubarray(S));
 
}
}
 
// This code contributed by gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
     
    # Initializing i and j as left and
    # right boundaries of sliding window
    i = 0
    j = 0
    k = 1
 
    for j in range(len(s)):
         
        # If current character is '0'
        if (s[j] == '0'):
 
            # Decrement k by one
            k -= 1
 
        # If k is less than zero and character
        # at ith index is '0'
        if (k < 0 ):
            if s[i] == '0':
                k += 1
                 
            i += 1
             
    j += 1
 
    # Return result
    return j - i - 1
 
# Driver Code
if __name__ == "__main__" :
 
    S = "011101101"
     
    print(longestSubarray(S))
 
# This code is contributed by AnkThon

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(string s)
{
     
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for(j = 0; j < s.Length; ++j)
    {
         
        // If current character is '0'
        if (s[j] == '0')
         
            // Decrement k by one
            k -= 1;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void Main(string[] args)
{
    string S = "011101101";
     
    Console.Write(longestSubarray(S));
}
}
 
// This code is contributed by AnkThon

chevron_right


Output: 

5

 

Time complexity: O(N)
Auxiliary Space: O(N)

 

competitive-programming-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :