Given a string str consisting of lowercase English letters and an integer K. The task is to find the minimum length of the sub-string whose characters can be used to form a palindrome of length K. If no such sub-string exists then print -1.
Input: str = “abcda”, k = 2
In order to form a palindrome of length 2, both the occurrences of ‘a’ are required.
Hence, the length of the required sub-string will be 5.
Input: str = “abcde”, k = 5
No palindromic string of length 5 can be formed from the characters of the given string.
Approach: The idea is to use Binary Search. Minimum character needed to form a palindrome of length K is K. So, our search domain gets reduced to [K, length(str)]. Apply binary search in this range and find a sub-string of length X (K ≤ X ≤ length(S)) such that using some or all characters of this sub-string a palindromic string of size K can be formed. Minimum X which satisfies the given condition will be the required answer. If no such such sub-string is possible then print -1.
Below is the implementation of the above approach:
- Minimum length substring with exactly K distinct characters
- Length of the longest substring that do not contain any palindrome
- Maximum length substring having all same characters after k changes
- Length of the longest substring without repeating characters
- Maximum length palindrome that can be created with characters in range L and R
- Minimum K such that every substring of length atleast K contains a character c
- Rearrange characters to form palindrome if possible
- Check if characters of a given string can be rearranged to form a palindrome
- Nth Even length Palindrome
- Length of the longest substring with equal 1s and 0s
- Find max length odd parity substring
- Length of the longest valid substring
- Longest Even Length Substring such that Sum of First and Second Half is same
- Check if the characters in a string form a Palindrome in O(1) extra space
- Sum of first K even-length Palindrome numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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 : AnkitRai01