Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times.
Input : str = "geeksforgeeks" k = 2 Output : geeksgeeks Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb" k = 5 Output : aabbaabaabb
Method 1 (Brute force)
We generate all subsequences. For every subsequence count distinct characters in it and find the longest subsequence where every character appears at-least k times.
Method 2 (Efficient way)
1. Find the frequency of the string and store it in an integer array of size 26 representing the alphabets.
2. After finding the frequency iterate the string character by character and if the frequency of that character is greater than or equal to the required number of repetitions then print that character then and there only.
This code has a time complexity of O(n) where n is the size of the string.
This article is contributed by Mohak Agrawal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Return maximum occurring character in an input string
- Given a string, find its first non-repeating character
- Longest Common Subsequence | DP-4
- Length of the longest substring without repeating characters
- Longest Non-palindromic substring
- Longest Palindromic Subsequence | DP-12
- Longest Palindromic Substring | Set 1
- Longest Palindromic Substring | Set 2
- Longest Common Substring | DP-29
- Find the first non-repeating character from a stream of characters
- Maximum length prefix of one string that occurs as subsequence in another
- Printing Longest Common Subsequence
- Given two strings, find if first string is a subsequence of second
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- Longest Even Length Substring such that Sum of First and Second Half is same
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Find the longest substring with k unique characters in a given string