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 Divide and Conquer
  • MCQs on Divide and Conquer
  • Tutorial on Divide & Conquer
  • Binary Search
  • Merge Sort
  • Quick Sort
  • Calculate Power
  • Strassen's Matrix Multiplication
  • Karatsuba Algorithm
  • Divide and Conquer Optimization
  • Closest Pair of Points
Open In App
Next Article:
Minimum K such that every substring of length at least K contains a character c | Set-2
Next article icon

Minimum K such that every substring of length atleast K contains a character c

Last Updated : 13 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : Every substring of length atleast 3 contains character ‘c’, i.e. 
{“abc”, “bcd”, “cde”, “abcd”, “bcde”, “abcde”} 

Input :S = “aaaa” 
Output :1

Prerequisites : Binary Search

Naive Solution : A simple approach is to iterate over all possible lengths of substrings i.e. from 1 to N (size of string) and for every current length substrings check whether some character appears in all of those substrings.

Efficient Solution : 

The key idea is to perform binary search over the answer K, since if some character c appears in all substrings of length X, it will always appear in all substrings of length (X + 1). Hence, we can check for the current length and try to minimise it using divide and conquer algorithm. For checking if some character appears in all substrings of length X, iterate over all characters from ‘a’ to ‘z’ and inside another loop iteratively store the last occurrence of the last character. 

Let the current position be j, so the last substring of length X will be from (j – X) to X. Check if the position of last occurrence of current K-amazing character is greater than (j – X) or not. If it is greater, then that substring is a valid string.

Below is the implementation of the above approach. 

C++




// CPP Program to find minimum K such that
// every substring of length atleast K
// contains some character c
#include <bits/stdc++.h>
using namespace std;
 
// This function checks if there exists some
// character which appears in all K length
// substrings
int check(string s, int K)
{
    // Iterate over all possible characters
    for (int ch = 0; ch < 26; ch++) {
        char c = 'a' + ch;
 
        // stores the last occurrence
        int last = -1;
 
        // set answer as true;
        bool found = true;
        for (int i = 0; i < K; i++)
            if (s[i] == c)
                last = i;
 
        // No occurrence found of current
        // character in first substring
        // of length K
        if (last == -1)
            continue;
 
        // Check for every last substring
        // of length K where last occurr-
        // ence exists in substring
        for (int i = K; i < s.size(); i++) {
            if (s[i] == c)
                last = i;
 
            // If last occ is not
            // present in substring
            if (last <= (i - K)) {
                found = false;
                break;
            }
        }
        // current character is K amazing
        if (found)
            return 1;
    }
    return 0;
}
 
// This function performs binary search over the
// answer to minimise it
int binarySearch(string s)
{
    int low = 1, high = (int)s.size();
    int ans;
    while (low <= high) {
        int mid = (high + low) >> 1;
 
        // Check if answer is found try
        // to minimise it
        if (check(s, mid)) {
            ans = mid;
            high = mid - 1;
        }
        else
            low = mid + 1;
    }
    return ans;
}
 
// Driver Code to test above functions
int32_t main()
{
    string s = "abcde";
    cout << binarySearch(s) << endl;
 
    s = "aaaa";
    cout << binarySearch(s) << endl;
    return 0;
}
 
 

Java




// Java Program to find minimum K such that
// every substring of length atleast K
// contains some character c
 
class GFG
{
     
         
        // This function checks if there exists some
        // character which appears in all K length
        // substrings
        static int check(String s, int K)
        {
            // Iterate over all possible characters
            for (int ch = 0; ch < 26; ch++) {
                char c = (char)( 'a' + ch);
         
                // stores the last occurrence
                int last = -1;
         
                // set answer as true;
                boolean found = true;
                for (int i = 0; i < K; i++)
                    if (s.charAt(i) == c)
                        last = i;
         
                // No occurrence found of current
                // character in first substring
                // of length K
                if (last == -1)
                    continue;
         
                // Check for every last substring
                // of length K where last occurr-
                // ence exists in substring
                for (int i = K; i < s.length(); i++) {
                    if (s.charAt(i) == c)
                        last = i;
         
                    // If last occ is not
                    // present in substring
                    if (last <= (i - K)) {
                        found = false;
                        break;
                    }
                }
                // current character is K amazing
                if (found)
                    return 1;
            }
            return 0;
        }
         
        // This function performs binary search over the
        // answer to minimise it
        static int binarySearch(String s)
        {
            int low = 1, high = s.length();
            int ans=0;
            while (low <= high) {
                int mid = (high + low) >> 1;
         
                // Check if answer is found try
                // to minimise it
                if (check(s, mid)==1) {
                    ans = mid;
                    high = mid - 1;
                }
                else
                    low = mid + 1;
            }
            return ans;
        }
         
        // Driver Code to test above functions
        public static void main(String args[])
        {
            String s = "abcde";
            System.out.println(binarySearch(s));
         
            s = "aaaa";
            System.out.println(binarySearch(s));
     
        }
 
}
 
// This article is contributed
// by ihritik
 
 

Python3




# Python3 Program to find minimum K such
# that every substring of length atleast
# K contains some character c
 
# This function checks if there exists
# some character which appears in all
# K length substrings
def check(s, K):
 
    # Iterate over all possible characters
    for ch in range(0, 26):
        c = chr(97 + ch) # Ascii value of 'a' => 97
 
        # stores the last occurrence
        last = -1
 
        # set answer as true
        found = True
        for i in range(0, K):
            if s[i] == c:
                last = i
 
        # No occurrence found of current character
        # in first substring of length K
        if last == -1:
            continue
 
        # Check for every last substring
        # of length K where last occurr-
        # ence exists in substring
        for i in range(K, len(s)):
            if s[i] == c:
                last = i
 
            # If last occ is not
            # present in substring
            if last <= (i - K):
                found = False
                break
             
        # current character is K amazing
        if found:
            return 1
     
    return 0
 
# This function performs binary search
# over the answer to minimise it
def binarySearch(s):
 
    low, high, ans = 1, len(s), None
     
    while low <= high:
        mid = (high + low) >> 1
 
        # Check if answer is found
        # try to minimise it
        if check(s, mid):
            ans, high = mid, mid - 1
         
        else:
            low = mid + 1
     
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    s = "abcde"
    print(binarySearch(s))
 
    s = "aaaa"
    print(binarySearch(s))
 
# This code is contributed by Rituraj Jain
 
 

C#




// C# Program to find minimum K such that
// every substring of length atleast K
// contains some character c
 
using System;
class GFG
{
     
         
        // This function checks if there exists some
        // character which appears in all K length
        // substrings
        static int check(String s, int K)
        {
            // Iterate over all possible characters
            for (int ch = 0; ch < 26; ch++) {
                char c = (char)( 'a' + ch);
         
                // stores the last occurrence
                int last = -1;
         
                // set answer as true;
                bool found = true;
                for (int i = 0; i < K; i++)
                    if (s[i] == c)
                        last = i;
         
                // No occurrence found of current
                // character in first substring
                // of length K
                if (last == -1)
                    continue;
         
                // Check for every last substring
                // of length K where last occurr-
                // ence exists in substring
                for (int i = K; i < s.Length; i++) {
                    if (s[i] == c)
                        last = i;
         
                    // If last occ is not
                    // present in substring
                    if (last <= (i - K)) {
                        found = false;
                        break;
                    }
                }
                // current character is K amazing
                if (found)
                    return 1;
            }
            return 0;
        }
         
        // This function performs binary search over the
        // answer to minimise it
        static int binarySearch(String s)
        {
            int low = 1, high = s.Length;
            int ans=0;
            while (low <= high) {
                int mid = (high + low) >> 1;
         
                // Check if answer is found try
                // to minimise it
                if (check(s, mid)==1) {
                    ans = mid;
                    high = mid - 1;
                }
                else
                    low = mid + 1;
            }
            return ans;
        }
         
        // Driver Code to test above functions
        public static void Main()
        {
            String s = "abcde";
            Console.WriteLine(binarySearch(s));
         
            s = "aaaa";
            Console.WriteLine(binarySearch(s));
     
        }
 
}
 
// This article is contributed
// by ihritik
 
 

PHP




<?php
// Php Program to find minimum K such that
// every substring of length atleast K
// contains some character c
 
// This function checks if there exists some
// character which appears in all K length
// substrings
function check($s, $K)
{
    // Iterate over all possible characters
    for ($ch = 0; $ch < 26; $ch++)
    {
        $c = chr(ord('a') + $ch) ;
 
        // stores the last occurrence
        $last = -1;
 
        // set answer as true;
        $found = true;
        for ($i = 0; $i < $K; $i++)
            if ($s[$i] == $c)
                $last = $i;
 
        // No occurrence found of current
        // character in first substring
        // of length K
        if ($last == -1)
            continue;
 
        // Check for every last substring
        // of length K where last occurr-
        // ence exists in substring
        for ($i = $K; $i < strlen($s); $i++)
        {
            if ($s[$i] == $c)
                $last = $i;
 
            // If last occ is not
            // present in substring
            if ($last <= ($i - $K))
            {
                $found = false;
                break;
            }
        }
         
        // current character is K amazing
        if ($found)
            return 1;
    }
    return 0;
}
 
// This function performs binary search
// over the answer to minimise it
function binarySearch($s)
{
    $low = 1 ;
    $high = strlen($s) ;
    while ($low <= $high)
    {
        $mid = ($high + $low) >> 1;
 
        // Check if answer is found try
        // to minimise it
        if (check($s, $mid))
        {
            $ans = $mid;
            $high = $mid - 1;
        }
        else
            $low = $mid + 1;
    }
    return $ans;
}
 
// Driver Code
$s = "abcde";
echo binarySearch($s) . "\n";
 
$s = "aaaa";
echo binarySearch($s) . "\n";
 
// This code is contributed by Ryuga
?>
 
 

Javascript




<script>
 
// Javascript Program to find minimum K such that
// every substring of length atleast K
// contains some character c
 
// This function checks if there exists some
// character which appears in all K length
// substrings
function check(s, K)
{
    // Iterate over all possible characters
    for (var ch = 0; ch < 26; ch++) {
        var c = String.fromCharCode('a'.charCodeAt(0) + ch);
 
        // stores the last occurrence
        var last = -1;
 
        // set answer as true;
        var found = true;
        for (var i = 0; i < K; i++)
            if (s[i] == c)
                last = i;
 
        // No occurrence found of current
        // character in first substring
        // of length K
        if (last == -1)
            continue;
 
        // Check for every last substring
        // of length K where last occurr-
        // ence exists in substring
        for (var i = K; i < s.length; i++) {
            if (s[i] == c)
                last = i;
 
            // If last occ is not
            // present in substring
            if (last <= (i - K)) {
                found = false;
                break;
            }
        }
        // current character is K amazing
        if (found)
            return 1;
    }
    return 0;
}
 
// This function performs binary search over the
// answer to minimise it
function binarySearch(s)
{
    var low = 1, high = s.length;
    var ans;
    while (low <= high) {
        var mid = (high + low) >> 1;
 
        // Check if answer is found try
        // to minimise it
        if (check(s, mid)) {
            ans = mid;
            high = mid - 1;
        }
        else
            low = mid + 1;
    }
    return ans;
}
 
// Driver Code to test above functions
var s = "abcde";
document.write( binarySearch(s) + "<br>");
s = "aaaa";
document.write( binarySearch(s) );
 
</script>
 
 
Output
3 1 

Complexity Analysis:

  • Time Complexity: O(N * logN * 26), where N is the size of the given string.
  • Auxiliary Space: O(1) because constant space is used. 


Next Article
Minimum K such that every substring of length at least K contains a character c | Set-2

N

Nishant Tanwar
Improve
Article Tags :
  • Algorithms
  • Divide and Conquer
  • DSA
  • Strings
  • Binary Search
  • substring
  • Technical Scripter 2018
Practice Tags :
  • Algorithms
  • Binary Search
  • Divide and Conquer
  • Strings

Similar Reads

  • 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
  • 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
  • Modify string by inserting characters such that every K-length substring consists of unique characters only
    Given string S of size N consisting of K distinct characters and (N - K) '?'s, the task is to replace all '?' with existing characters from the string such that every substring of size K has consisted of unique characters only. If it is not possible to do so, then print "-1". Examples: Input: S = "?
    6 min read
  • Count of substrings of length K with exactly K-1 distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all substrings of length k which have exactly k-1 distinct characters. Example: Input: s = "abcc", k = 2 Output: 1Explanation: Substrings of length 2 are "ab", "bc" and "cc". Only "cc" has 2-1 = 1 distinct chara
    7 min read
  • Minimum string such that every adjacent character of given string is still adjacent
    Given a string S, the task is to find the minimum length string such that every adjacent character of the string remains adjacent in the minimum length string. Examples: Input: S = "acabpba" Output: pbac Explanation: The given string can be converted to "pbac" in which, every adjacent character rema
    13 min read
  • Minimize length of Substrings containing at least one common Character
    Given a string str, the task is to find the minimum length of substrings such that all the sub strings of that length from str contains at least one common character. If no such length can be obtained, print -1. Example: Input: str = "saad" Output: 2 Explanation: All the substrings of length two of
    10 min read
  • Number of substrings with count of each character as k
    Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. Examples: Input : s = "aabbcc" k = 2 Output : 6 The substrings are aa, bb, cc, aabb, bbcc and aabbcc. Input : s = "aabccc" k = 2 Output : 3 There are three substrings aa, cc an
    15 min read
  • Length of longest substring having all characters as K
    Given a string S and a character K. The task is to find the length of the longest substring of S having all characters the same as character K. Examples: Input: S = "abcd1111aabc", K = '1' Output: 4 Explanation: 1111 is the largest substring of length 4. Input: S = "#1234#@@abcd", K = '@' Output: 2
    8 min read
  • Minimum value of K such that each substring of size K has the given character
    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 sub
    12 min read
  • Count number of substrings having at least K distinct characters
    Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters. Examples: Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are: "abc": Count of dist
    7 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