Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Number of sub-strings that contain the given character exactly k times
Next article icon

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

Last Updated : 23 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Number of sub-strings that contain the given character exactly k times

S

subhankarjadab
Improve
Article Tags :
  • DSA
  • Mathematical
  • Strings
  • substring
Practice Tags :
  • Mathematical
  • Strings

Similar Reads

  • Number of sub-strings that contain the given character exactly k times
    Given the string str, a character c, and an integer k > 0. The task is to find the number of sub-strings that contain the character c exactly k times.Examples: Input: str = "abada", c = 'a', K = 2 Output: 4 All possible sub-strings are "aba", "abad", "bada" and "ada". Input: str = "55555", c = '5
    10 min read
  • Minimum length String with Sum of the alphabetical values of the characters equal to N
    Given an integer N, the task is to find the minimum length string whose sum of each character (As a = 1, b = 2, ... z = 26) equals to N.Examples: Input: N = 5 Output: e 5 can be represented as "aac" or "ad" or "e" etc But we will take e as it is the minimum length Input: N = 34 Output: zj Approach:
    4 min read
  • Minimum number of swaps required such that a given substring consists of exactly K 1s
    Given a binary string S of size N and three positive integers L, R, and K, the task is to find the minimum number of swaps required to such that the substring {S[L], .. S[R]} consists of exactly K 1s. If it is not possible to do so, then print "-1". Examples: Input: S = "110011111000101", L = 5, R =
    11 min read
  • Minimum K such that every substring of length at least K contains a character c | Set-2
    Given a string S consisting of N lowercase English alphabets, and also given that a character C is called K-amazing, if every substring of length at least K contains this character C, the task is to find the minimum possible K such that there exists at least one K-amazing character. Examples: Input:
    8 min read
  • Minimum partitions of String such that each part is at most K
    Given a string S of size N consisting of numerical digits 1-9 and a positive integer K, the task is to minimize the partitions of the string such that each part is at most K. If it’s impossible to partition the string print -1. Examples: Input: S = "3456", K = 45Output: 2Explanation: One possible wa
    8 min read
  • Find the minimum possible sum that can be made by the digits of given String
    Given a string S of length N along with K, the task is to output the minimum sum of suffix after making the longest prefix of zeros that can be obtained by applying the given operation at most K times. Then you can apply the given operation on S: Choose an index let's say i (1 <= i <= N)Do thi
    15+ min read
  • Minimum K such that every substring of length atleast K contains a character c
    Given a string S containing lowercase latin letters. A character c is called K-amazing if every substring of S with length atleast K contains this character c. Find the minimum possible K such that there exists atleast one K-amazing character. Examples: Input : S = "abcde" Output :3 Explanation : Ev
    11 min read
  • Remove k characters in a String such that ASCII sum is minimum
    Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2
    7 min read
  • Generate a string of size N whose each substring of size M has exactly K distinct characters
    Given 3 positive integers N, M, and K. the task is to construct a string of length N consisting of lowercase letters such that each substring of length M having exactly K distinct letters.Examples: Input: N = 5, M = 2, K = 2 Output: abade Explanation: Each substring of size 2 "ab", "ba", "ad", "de"
    6 min read
  • Minimize deletions such that sum of position of characters is at most K
    Given a string S consisting of lower case letters and an integer K, the task is to remove minimum number of letters from the string, such that the sum of alphabetic ordering of the letters present in the string is at most K. Examples : Input: S = "abca", K = 2Output: "aa"Explanation: Initial sum for
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences