Skip to content
Related Articles
Open in App
Not now

Related Articles

Longest Substring with at most X 0s and Y 1s of given String

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 11 Apr, 2022
Improve Article
Save Article

Given a binary string S of length N, the task is to find the longest substring with at most X number of 0’s and Y number of 1’s.

Example:

Input: S = “10101”, N = 5,  X = 1, Y = 2
Output: 3
Explanation: The longest substring with at most 1 zero and 2 ones is “101” with length 3.

Input: S = “111”, N = 3, X = 1, Y = 1
Output: 1
Explanation: longest substring with at most 1 zero and 1 one is “1” with length 1.

Input: S = “00000”, N = 5, X = 0, Y = 1
Output: 0
Explanation: No substrings exists with at most 0 number of zero’s and 1 number of one’s as whole string does not contain 1’s anywhere.

 

Naive Approach: The naive approach to solve this problem is to find all the substrings and for each substring count the number of 0’s and 1’s in the substring and check if the counts of those are at most X and Y respectively. 

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

Efficient Approach: This problem can be solved using the concept of two pointer approach based on the following idea: 

Use two pointers (i, j), Where j is the last pointer and i is the starting pointer. Use those pointers to keep track of number of 0s and 1s in that range and update those based on the count of 0s and 1s in that range to adjust the substring length. 

  • Increment the last pointer till the any one of the count of 0s and 1s does not exceed their upper limit. 
  • If any of their count exceeds the provided limit then increment the first pointer to decrease the range.
  • The longest range will give the longest substring.

Follow the below steps to solve this problem.

  • Initialize i, j and maxLength to 0.
  • Traverse while j < N.
    • Count the number of 0’s and 1’s which is ending at jth index.
    • Check if the number of 0’s and 1’s satisfies the given condition.
    • If yes, then calculate the size of the current substring which is starting at i and ending at j.
      • If the calculated size is greater than maxLength then, update the maxLength.
    • Otherwise, reduce the count of characters which is at ith index and increment the value of i.
  • Return maxLength as the final answer.

Below is the implementation of the above approach:

C++14




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the longest substring
// with at most X number of 0's
// and Y number of 1's
int longestKSubarray(string& S, int X, int Y)
{
    int N = S.length(), i = 0, j = 0;
    int count0 = 0, count1 = 0, maxLength = 0;
 
    while (j < N) {
 
        // Increment the count of jth character
        if (S[j] == '0') {
            count0++;
        }
        else {
            count1++;
        }
 
        // Check for Given condition
        if (count0 > X || count1 > Y) {
 
            // Reduce the count of ith character
            if (S[i] == '0') {
                count0--;
            }
            else {
                count1--;
            }
 
            // Move the ith pointer
            i++;
        }
 
        // Move the jth pointer
        j++;
 
        // Keep Updating the maxLength.
        maxLength = max(maxLength, j - i);
    }
    return maxLength;
}
 
// Driver's code
int main()
{
    string S = "10101";
    int X = 1, Y = 2;
 
    // Function call
    cout << longestKSubarray(S, X, Y);
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG {
 
  // Function to find the longest substring
  // with at most X number of 0's
  // and Y number of 1's
  static int longestKSubarray(String S, int X, int Y)
  {
    int N = S.length(), i = 0, j = 0;
    int count0 = 0, count1 = 0, maxLength = 0;
 
    while (j < N) {
 
      // Increment the count of jth character
      if (S.charAt(j) == '0') {
        count0++;
      }
      else {
        count1++;
      }
 
      // Check for Given condition
      if (count0 > X || count1 > Y) {
 
        // Reduce the count of ith character
        if (S.charAt(i) == '0') {
          count0--;
        }
        else {
          count1--;
        }
 
        // Move the ith pointer
        i++;
      }
 
      // Move the jth pointer
      j++;
 
      // Keep Updating the maxLength.
      maxLength = Math.max(maxLength, j - i);
    }
    return maxLength;
  }
 
  // Driver's code
  public static void main (String[] args) {
 
    String S = "10101";
    int X = 1, Y = 2;
 
    // Function call
    System.out.print(longestKSubarray(S, X, Y));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python3 program to implement the above approach
 
# Function to find the longest substring
# with at most X number of 0's
# and Y number of 1's
def longestKSubarray(S, X, Y):
    N = len(S)
    i = 0
    j = 0
    count0 = 0
    count1 = 0
    maxLength = 0
    while j < N:
       
        # Increment the count of jth character
        if S[j] == "0":
            count0 += 1
        else:
            count1 += 1
 
        # Check for Given condition
        if count0 > X or count1 > Y:
           
            # Reduce the count of ith character
            if S[i] == "0":
                count0 -= 1
            else:
                count1 -= 1
                 
            # Move the ith pointer
            i += 1
             
        # Move the jth pointer
        j += 1
         
        # Keep Updating the maxLength.
        maxLength = max(maxLength, j - i)
    return maxLength
 
# Driver Code
S = "10101"
X = 1
Y = 2
 
# Function Call
print(longestKSubarray(S, X, Y))
 
# This code is contributed by phasing17


C#




// C# code to implement the approach
using System;
class GFG {
 
  // Function to find the longest substring
  // with at most X number of 0's
  // and Y number of 1's
  static int longestKSubarray(string S, int X, int Y)
  {
    int N = S.Length, i = 0, j = 0;
    int count0 = 0, count1 = 0, maxLength = 0;
 
    while (j < N) {
 
      // Increment the count of jth character
      if (S[j] == '0') {
        count0++;
      }
      else {
        count1++;
      }
 
      // Check for Given condition
      if (count0 > X || count1 > Y) {
 
        // Reduce the count of ith character
        if (S[i] == '0') {
          count0--;
        }
        else {
          count1--;
        }
 
        // Move the ith pointer
        i++;
      }
 
      // Move the jth pointer
      j++;
 
      // Keep Updating the maxLength.
      maxLength = Math.Max(maxLength, j - i);
    }
    return maxLength;
  }
 
  // Driver's code
  public static void Main()
  {
 
    string S = "10101";
    int X = 1, Y = 2;
 
    // Function call
    Console.Write(longestKSubarray(S, X, Y));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
    // JavaScript code to implement the approach
 
 
    // Function to find the longest substring
    // with at most X number of 0's
    // and Y number of 1's
    const longestKSubarray = (S, X, Y) => {
        let N = S.length, i = 0, j = 0;
        let count0 = 0, count1 = 0, maxLength = 0;
 
        while (j < N) {
 
            // Increment the count of jth character
            if (S[j] == '0') {
                count0++;
            }
            else {
                count1++;
            }
 
            // Check for Given condition
            if (count0 > X || count1 > Y) {
 
                // Reduce the count of ith character
                if (S[i] == '0') {
                    count0--;
                }
                else {
                    count1--;
                }
 
                // Move the ith pointer
                i++;
            }
 
            // Move the jth pointer
            j++;
 
            // Keep Updating the maxLength.
            maxLength = Math.max(maxLength, j - i);
        }
        return maxLength;
    }
 
    // Driver's code
 
    let S = "10101";
    let X = 1, Y = 2;
 
    // Function call
    document.write(longestKSubarray(S, X, Y));
 
// This code is contributed by rakeshsahni
 
</script>


Output

3

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!