Given a string of lowercase English alphabets and an integer 0 < K <= 26. The task is to divide the string into two parts (also print them) such that both parts have at least k different characters. If there are more than one answers possible, print one having the smallest left part. If there is no such answers, print “Not Possible”.
Input : str = “geeksforgeeks”, k = 4
Output : geeks , forgeeks
The string can be divided into two parts as “geeks” and “forgeeks”. Since “geeks” has four different characters ‘g’, ‘e’, ‘k’ and ‘s’ and this is the smallest left part, “forgeeks” has also at least four different characters.
Input : str = “aaaabbbb”, k = 2
Output :Not Possible
- Idea is to count the number of distinct characters using a Hashmap.
- If the count of the distinct variable becomes equal to k, then the left part of the string is found so store this index, break the loop and unmark all the characters.
- Now run a loop from where the left string ends to end of the given string and repeat the same process as it was done to find the left string.
- If count is greater than or equal to k, then right string could be found otherwise print “Not Possible”.
- If it is possible , then print the left string and right string.
Below is the implementation of the above approach
Time Complexity: O(N) where N is the length of given string.
- Split a string in equal parts such that all parts are palindromes
- Partition a number into two divisible parts
- Divide a string in N equal parts
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Divide a number into two parts
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Min flips of continuous characters to make all characters same in a string
- String with k distinct characters and no same characters adjacent
- Maximum String Partition
- Number of ways to partition a string into two balanced subsequences
- Ways to split string such that each partition starts with distinct character
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Minimal moves to form a string by adding characters or appending string itself
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
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.