Open In App

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

Last Updated : 23 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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”.

Implementation:- 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
//Function to check character c in all substring of size i in s
bool ispresent(int i,string s,char c)
{
      int j=0;
       
      //map to store the elements which are present in current substring
      //of length i
      unordered_map<int,int> mm;
      //iterating over all length string of size i
      for(int k=0;k<s.length();k++)
    {
          mm[s[k]]++;
          if(k-j+1==i)
        {
              //if character c is not present return false
              if(mm==0)return false;
              mm[s[j]]--;
              j++;
        }
    }
  return true;   
}
 
// 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)
{
      //Loop for substring of size 1 to N
      for(int i=1;i<=s.length();i++)
    {
          //if all substring of size i have charachetr c
          if(ispresent(i,s,c))return i;
    }
  return -1;
}
 
// Driver Code
int main() {
    string S = "abdegb";
    char ch = 'b';
    cout<<(findK(S, ch));
    return 0;
}
 
 
// This code is contributed by shubhamrajput6156


Java




// JAVA program for the above approach
 
import java.util.*;
 
public class GFG {
  //Function to check character c in all substring of size i in s
    static boolean ispresent(int i, String s, char c) {
        int j = 0;
 
        //map to store the elements which are present
        // in current substring of length i
        Map<Character, Integer> mm = new HashMap<>();
 
        //iterating over all length string of size
        for (int k = 0; k < s.length(); k++) {
            char currentChar = s.charAt(k);
            mm.put(currentChar, mm.getOrDefault(currentChar, 0) + 1);
            if (k - j + 1 == i) {
                 
                //if character c is not present return false
                if (!mm.containsKey(c))
                    return false;
                     
                int count = mm.get(s.charAt(j));
                if (count == 1) {
                    mm.remove(s.charAt(j));
                } else {
                    mm.put(s.charAt(j), count - 1);
                }
                j++;
            }
        }
        return true;
    }
 
    // Function to find the minimum value
    // of K such that char c occurs in all
    // K sized substrings of string S
    static int findK(String s, char c) {
         
        //Loop for substring of size 1 to N
        for (int i = 1; i <= s.length(); i++) {
            //if all substring of size i have charachetr c
            if (ispresent(i, s, c))
            return i;
        }
        return -1;
    }
 
    // 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 bhardwajji


Python3




# Python program for the above approach
 
# Function to check character c in all substring of size i in s
def ispresent(i, s, c):
    j = 0
     
    # dictionory to store the elements which are present in current substring
    # of length i
    mm = {}
     
    # iterating over all length string of size i
    for k in range(len(s)):
        if s[k] in mm:
            mm[s[k]] += 1
        else:
            mm[s[k]] = 1
        if k - j + 1 == i:
           
              # if character c is not present return false
            if c not in mm:
                return False
            mm[s[j]] -= 1
            if mm[s[j]] == 0:
                del mm[s[j]]
            j += 1
    return True
 
# 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):
   
      # Loop for substring of size 1 to N
    for i in range(1, len(s) + 1):
       
          # if all substring of size i have charachetr c
        if ispresent(i, s, c):
            return i
    return -1
 
#driver code
S = "abdegb"
ch = "b"
print(findK(S, ch))


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
public class GFG
{
    // Function to check character c in all substring of size i in s
    static bool ispresent(int i, string s, char c)
    {
        int j = 0;
 
        // Dictionary to store the elements which are present in current substring
        // of length i
        Dictionary<char, int> mm = new Dictionary<char, int>();
       
        // iterating over all length string of size i
        for (int k = 0; k < s.Length; k++)
        {
            if (!mm.ContainsKey(s[k]))
            {
                mm[s[k]] = 0;
            }
            mm[s[k]]++;
            if (k - j + 1 == i)
            {
                // if character c is not present return false
                if (mm.ContainsKey(c) && mm == 0) return false;
                mm[s[j]]--;
                j++;
            }
        }
        return true;
    }
     
    // Function to find the minimum value
    // of K such that char c occurs in all
    // K sized substrings of string S
    static int findK(string s, char c)
    {
        // Loop for substring of size 1 to N
        for (int i = 1; i <= s.Length; i++)
        {
            // if all substring of size i have character c
            if (ispresent(i, s, c)) return i;
        }
        return -1;
    }
     
    // Driver Code
    public static void Main()
    {
        string S = "abdegb";
        char ch = 'b';
        Console.WriteLine(findK(S, ch));
    }
}
 
 
// This code is contributed by bhardwajji


Javascript




// Function to check character c in all substring of size i in s
function ispresent(i, s, c) {
    let j = 0;
    let mm = {};
    for (let k = 0; k < s.length; k++) {
        if (mm[s[k]]) {
            mm[s[k]] += 1;
        } else {
            mm[s[k]] = 1;
        }
        if (k - j + 1 == i) {
            if (!mm) {
                return false;
            }
            mm[s[j]] -= 1;
            if (mm[s[j]] == 0) {
                delete mm[s[j]];
            }
            j += 1;
        }
    }
    return true;
}
 
// 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) {
    for (let i = 1; i <= s.length; i++) {
        if (ispresent(i, s, c)) {
            return i;
        }
    }
    return -1;
}
 
// driver code
let S = "abdegb";
let ch = "b";
console.log(findK(S, ch));


Output

4

Time Complexity: O(N^2)
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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads