Skip to content
Related Articles

Related Articles

Minimum value of K such that each substring of size K has the given character

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 30 Jun, 2022
Improve Article
Save Article

Given a string of lowercase letters S a character c. The task is to find minimum K such that every substring of length K contains the given character c. If there is no such K possible, return -1.
Examples:

Input: S = “abdegb”, ch = ‘b’
Output: 4 
Explanation:
Consider the value of K as 4. Now, every substring of size K(= 4) are {“abde”, “bdeg”, “degb” } has the character ch(= b’).

Input: S = “abfge”, ch = ‘m’
Output : -1

 

Naive Approach: The simplest approach to solve the given problem is to iterate for all possible sizes of substrings over the range [1, N] and check which minimum value of K satisfies the given criteria. If there doesn’t exist any such value of K, then print “-1”.

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

Efficient Approach: The above approach can also be optimized by using an observation that the minimum value of K is equal to the maximum difference between the consecutive occurrences of the given character ch as for every substring of size K there must have at least 1 character as ch. Follow the steps below to solve the given problem:

  • Initialize a variable, say maxDifference as -1 that store the resultant value of K.
  • Initialize a variable, say previous as 0 that store the previous occurrence of the character ch in the string S.
  • Traverse the given string S using the variable i and if the current character is ch then update the value of maxDifference to the maximum of maxDifference and (i – previous) and the value of previous to i.
  • After completing the above steps, print the value of maxDifference as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum value
// of K such that char c occurs in all
// K sized substrings of string S
int findK(string s, char c)
{
   
    // Store the string length
    int n = s.size();
 
    // Store difference of lengths
    // of segments of every two
    // consecutive occurrences of c
    int diff;
 
    // Stores the maximum difference
    int max = 0;
 
    // Store the previous occurrence
    // of char c
    int prev = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Check if the current character
        // is c or not
        if (s[i] == c) {
 
            // Stores the difference of
            // consecutive occurrences of c
            diff = i - prev;
 
            // Update previous occurrence
            // of c with current occurrence
            prev = i;
 
            // Comparing diff with max
            if (diff > max) {
                max = diff;
            }
        }
    }
 
    // If string doesn't contain c
    if (max == 0)
        return -1;
 
    // Return max
    return max;
}
 
// Driver Code
int main() {
    string S = "abdegb";
    char ch = 'b';
    cout<<(findK(S, ch));
    return 0;
}
 
 
// This code is contributed by 29AjayKumar

Java




// Java program for the above approach
class GFG {
 
    // Function to find the minimum value
    // of K such that char c occurs in all
    // K sized substrings of string S
    public static int findK(String s, char c)
    {
       
        // Store the string length
        int n = s.length();
 
        // Store difference of lengths
        // of segments of every two
        // consecutive occurrences of c
        int diff;
 
        // Stores the maximum difference
        int max = 0;
 
        // Store the previous occurrence
        // of char c
        int prev = 0;
 
        for (int i = 0; i < n; i++) {
 
            // Check if the current character
            // is c or not
            if (s.charAt(i) == c) {
 
                // Stores the difference of
                // consecutive occurrences of c
                diff = i - prev;
 
                // Update previous occurrence
                // of c with current occurrence
                prev = i;
 
                // Comparing diff with max
                if (diff > max) {
                    max = diff;
                }
            }
        }
 
        // If string doesn't contain c
        if (max == 0)
            return -1;
 
        // Return max
        return max;
    }
 
    // Driver Code
    public static void main(String args[]) {
        String S = "abdegb";
        char ch = 'b';
        System.out.println(findK(S, ch));
 
    }
}
 
// This code is contributed by saurabh_jaiswal.

Python3




# python program for the above approach
 
# Function to find the minimum value
# of K such that char c occurs in all
# K sized substrings of string S
def findK(s, c):
 
    # Store the string length
    n = len(s)
 
    # Store difference of lengths
    # of segments of every two
    # consecutive occurrences of c
    diff = 0
 
    # Stores the maximum difference
    max = 0
 
    # Store the previous occurrence
    # of char c
    prev = 0
 
    for i in range(0, n):
 
        # Check if the current character
        # is c or not
        if (s[i] == c):
 
            # Stores the difference of
            # consecutive occurrences of c
            diff = i - prev
 
            # Update previous occurrence
            # of c with current occurrence
            prev = i
 
            # Comparing diff with max
            if (diff > max):
                max = diff
 
    # If string doesn't contain c
    if (max == 0):
        return -1
 
    # Return max
    return max
 
 
# Driver Code
if __name__ == "__main__":
 
    S = "abdegb"
    ch = 'b'
    print(findK(S, ch))
 
# This code is contributed by rakeshsahni

C#




using System.Collections.Generic;
using System;
class GFG
{
 
    // Function to find the minimum value
    // of K such that char c occurs in all
    // K sized substrings of string S
    public static int findK(string s, char c)
    {
       
        // Store the string length
        int n = s.Length;
 
        // Store difference of lengths
        // of segments of every two
        // consecutive occurrences of c
        int diff;
 
        // Stores the maximum difference
        int max = 0;
 
        // Store the previous occurrence
        // of char c
        int prev = 0;
 
        for (int i = 0; i < n; i++) {
 
            // Check if the current character
            // is c or not
            if (s[i] == c) {
 
                // Stores the difference of
                // consecutive occurrences of c
                diff = i - prev;
 
                // Update previous occurrence
                // of c with current occurrence
                prev = i;
 
                // Comparing diff with max
                if (diff > max) {
                    max = diff;
                }
            }
        }
 
        // If string doesn't contain c
        if (max == 0)
            return -1;
 
        // Return max
        return max;
    }
 
    // Driver Code
    public static void Main()
  {
        string S = "abdegb";
        char ch = 'b';
        Console.WriteLine(findK(S, ch));
 
    }
}
 
// This code is contributed by amreshkumar3.

Javascript




<script>
// Javascript program for the above approach
 
// Function to find the minimum value
// of K such that char c occurs in all
// K sized substrings of string S
function findK(s, c)
{
 
  // Store the string length
  let n = s.length;
 
  // Store difference of lengths
  // of segments of every two
  // consecutive occurrences of c
  let diff;
 
  // Stores the maximum difference
  let max = 0;
 
  // Store the previous occurrence
  // of char c
  let prev = 0;
 
  for (let i = 0; i < n; i++) {
    // Check if the current character
    // is c or not
    if (s[i] == c) {
      // Stores the difference of
      // consecutive occurrences of c
      diff = i - prev;
 
      // Update previous occurrence
      // of c with current occurrence
      prev = i;
 
      // Comparing diff with max
      if (diff > max) {
        max = diff;
      }
    }
  }
 
  // If string doesn't contain c
  if (max == 0) return -1;
 
  // Return max
  return max;
}
 
// Driver Code
 
let S = "abdegb";
let ch = "b";
document.write(findK(S, ch));
 
// This code is contributed by saurabh_jaiswal.
</script>

Output: 

4

 

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!