Open In App

Longest subsequence where every character appears at-least k times

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times.

Examples: 

Input: str = “geeksforgeeks”, k = 2
Output: geeksgeeks
Explanation: Every character in the output subsequence appears at-least 2 times.

Input : str = “aabbaabacabb”, k = 5
Output : aabbaabaabb

Method 1 (Brute force): 

We can generate all possible subsequences of the given string and for each subsequence, we can count the frequency of each character in it. If the frequency of each character is at least k, then we can update our answer.

Implementation of the above approach:

C++





Java





Python3





C#





Javascript





Output

geeksgeeks

Time Complexity: O(2^n * n)

Auxiliary Space: O(n)

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. 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. 

Implementation:

C++





Java





Python3





C#





Javascript





Output

geeksgeeks

Time complexity: O(n), where n is the size of the string. 
Auxiliary Space: O(n), where n is the length of the string. This is because when a string is passed to any function it is passed by value and creates a copy of itself in the stack. 

Method 3 (Efficient way – Using HashMap) :

C++14





Java





Python3





C#





Javascript





Output

geeksgeeks

Time complexity: O(n*log(n)). This is because the time complexity of inserting an element in a map is O(log(n)).
Auxiliary Space: O(n), where n is the length of the string. This is because when the string is passed to any function it is passed by value and creates a copy of itself in the stack. 

 



Last Updated : 14 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads