Find length of longest substring with at most K normal characters

Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represent special character and 0 represent normal character for the 26 English alphabets. The task is to find the length of longest substring with at most K normal characters.

Examples:

Input : P = “normal”, Q = “00000000000000000000000000”, K=1
Output : 1
Explanation : In string Q all characters are normal.
Hence we can select any substring of length 1.

Input : P = “giraffe”, Q = “01111001111111111011111111”, K=2
Output : 3
Explanation : Normal characters in P from Q are {a, f, g, r}.
Therefore, possible substrings with at most 2 normal characters are {gir, ira, ffe}.
The maximum length of all substring is 3.

Approach:



To solve the problem mentioned above we will be using the concept of two pointers. Hence, maintain left and right pointers of the substring, and a count of normal characters. Increment right index till the count of normal characters is at most K. Then update the answer with a maximum length of substring encountered till now. Increment left index and decrement count till is it greater than K.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to Find
// length of longest substring
// with at most K normal characters
#include <bits/stdc++.h>
using namespace std;
  
// Function to find maximum
// length of normal substrings
int maxNormalSubstring(string& P, string& Q,
                       int K, int N)
{
  
    if (K == 0)
        return 0;
  
    // keeps count of normal characters
    int count = 0;
  
    // indexes of substring
    int left = 0, right = 0;
  
    // maintain length of longest substring
    // with at most K normal characters
    int ans = 0;
  
    while (right < N) {
  
        while (right < N && count <= K) {
  
            // get position of character
            int pos = P[right] - 'a';
  
            // check if current character is normal
            if (Q[pos] == '0') {
  
                // check if normal characters
                // count exceeds K
                if (count + 1 > K)
  
                    break;
  
                else
                    count++;
            }
  
            right++;
  
            // update answer with substring length
            if (count <= K)
                ans = max(ans, right - left);
        }
  
        while (left < right) {
  
            // get position of character
            int pos = P[left] - 'a';
  
            left++;
  
            // check if character is
            // normal then decrement count
            if (Q[pos] == '0')
  
                count--;
  
            if (count < K)
                break;
        }
    }
  
    return ans;
}
  
// Driver code
int main()
{
    // initialise the string
    string P = "giraffe", Q = "01111001111111111011111111";
  
    int K = 2;
  
    int N = P.length();
  
    cout << maxNormalSubstring(P, Q, K, N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to Find
// length of longest subString
// with at most K normal characters
class GFG{
   
// Function to find maximum
// length of normal subStrings
static int maxNormalSubString(char []P, char []Q,
                       int K, int N)
{
   
    if (K == 0)
        return 0;
   
    // keeps count of normal characters
    int count = 0;
   
    // indexes of subString
    int left = 0, right = 0;
   
    // maintain length of longest subString
    // with at most K normal characters
    int ans = 0;
   
    while (right < N) {
   
        while (right < N && count <= K) {
   
            // get position of character
            int pos = P[right] - 'a';
   
            // check if current character is normal
            if (Q[pos] == '0') {
   
                // check if normal characters
                // count exceeds K
                if (count + 1 > K)
   
                    break;
   
                else
                    count++;
            }
   
            right++;
   
            // update answer with subString length
            if (count <= K)
                ans = Math.max(ans, right - left);
        }
   
        while (left < right) {
   
            // get position of character
            int pos = P[left] - 'a';
   
            left++;
   
            // check if character is
            // normal then decrement count
            if (Q[pos] == '0')
   
                count--;
   
            if (count < K)
                break;
        }
    }
   
    return ans;
}
   
// Driver code
public static void main(String[] args)
{
    // initialise the String
    String P = "giraffe", Q = "01111001111111111011111111";
   
    int K = 2;
   
    int N = P.length();
   
    System.out.print(maxNormalSubString(P.toCharArray(), Q.toCharArray(), K, N));
}
}
  
// This code is contributed by Princi Singh

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

    
# Function to find maximum 
# length of normal substrings 
def maxNormalSubstring(P, Q, K, N): 
      
    if (K == 0):
        return 0 
    
    # keeps count of normal characters 
    count = 0 
    
    # indexes of substring 
    left, right = 0, 0
      
    # maintain length of longest substring 
    # with at most K normal characters 
    ans = 0
    
    while (right < N):
    
        while (right < N and count <= K):
    
            # get position of character 
            pos = ord(P[right]) - ord('a'
    
            # check if current character is normal 
            if (Q[pos] == '0'):
    
                # check if normal characters 
                # count exceeds K 
                if (count + 1 > K):
                    break
                else:
                    count += 1 
    
            right += 1 
    
            # update answer with substring length 
            if (count <= K):
                ans = max(ans, right - left)
    
        while (left < right): 
    
            # get position of character 
            pos = ord(P[left]) - ord('a')
    
            left += 1
    
            # check if character is 
            # normal then decrement count 
            if (Q[pos] == '0'):
                count -= 1 
    
            if (count < K):
                break 
    
    return ans
    
# Driver code 
if(__name__ == "__main__"):
    # initialise the string 
    P = "giraffe"
    Q = "01111001111111111011111111"
    
    K = 2
    
    N = len(P) 
    
    print(maxNormalSubstring(P, Q, K, N)) 
  
# This code is contributed by skylags

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to Find
// length of longest subString
// with at most K normal characters
using System;
  
public class GFG{
  
// Function to find maximum
// length of normal subStrings
static int maxNormalSubString(char []P, char []Q,
                    int K, int N)
{
  
    if (K == 0)
        return 0;
  
    // keeps count of normal characters
    int count = 0;
  
    // indexes of subString
    int left = 0, right = 0;
  
    // maintain length of longest subString
    // with at most K normal characters
    int ans = 0;
  
    while (right < N) {
  
        while (right < N && count <= K) {
  
            // get position of character
            int pos = P[right] - 'a';
  
            // check if current character is normal
            if (Q[pos] == '0') {
  
                // check if normal characters
                // count exceeds K
                if (count + 1 > K)
  
                    break;
  
                else
                    count++;
            }
  
            right++;
  
            // update answer with subString length
            if (count <= K)
                ans = Math.Max(ans, right - left);
        }
  
        while (left < right) {
  
            // get position of character
            int pos = P[left] - 'a';
  
            left++;
  
            // check if character is
            // normal then decrement count
            if (Q[pos] == '0')
  
                count--;
  
            if (count < K)
                break;
        }
    }
  
    return ans;
}
  
// Driver code
public static void Main(String[] args)
{
    // initialise the String
    String P = "giraffe", Q = "01111001111111111011111111";
  
    int K = 2;
  
    int N = P.Length;
  
    Console.Write(maxNormalSubString(P.ToCharArray(),
                     Q.ToCharArray(), K, N));
}
}
  
// This code contributed by Princi Singh

chevron_right


Output:

3

Time Complexity: The above method takes O(N) time.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.



Improved By : skylags, princi singh