Longest Substring with at most X 0s and Y 1s of given String
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.
Input: S = “10101”, N = 5, X = 1, Y = 2
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
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
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:
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...