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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Longest subsequence where each character occurs at least k times
- Check if max occurring character of one string appears same no. of times in other
- Lexicographically largest subsequence such that every character occurs at least k times
- Longest subsequence with at least one character appearing in every string
- Remove characters from a String that appears exactly K times
- Remove characters from string that appears strictly less than K times
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Minimum K such that every substring of length atleast K contains a character c
- NFA to accept strings that has atleast one character occurring in a multiple of 3
- Replace every character of string by character whose ASCII value is K times more than it
- Longest Common Prefix using Character by Character Matching
- Number of sub-strings that contain the given character exactly k times
- Count of substrings which contains a given character K times
- Encrypt a string by repeating i-th character i times
- Count substrings with each character occurring at most k times
- Print the string after the specified character has occurred given no. of times
- Decrypt a string encrypted by repeating i-th character i times
- Longest Palindromic Subsequence | DP-12
- Longest Uncommon Subsequence
- Longest Common Subsequence | DP-4