Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Longest subsequence where every character appears at-least k times

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




#include <iostream>
#include <cstring>
using namespace std;
 
void longestSubseqWithK(string str, int k)
{
    int n = str.length();
    string ans = "";
    int maxLen = 0;
     
    // Generate all possible subsequences using bit manipulation
    for (int i=0; i<(1<<n); i++) {
        string subseq = "";
        for (int j=0; j<n; j++) {
            if (i&(1<<j))
                subseq += str[j];
        }
         
        // Count frequency of each character in the subsequence
        int freq[26];
        memset(freq, 0, sizeof(freq));
        for (char c : subseq)
            freq[c-'a']++;
         
        // Check if each character appears at least k times
        bool flag = true;
        for (int f : freq) {
            if (f > 0 && f < k) {
                flag = false;
                break;
            }
        }
         
        // Update answer if the subsequence satisfies the condition
        if (flag && subseq.length() > maxLen) {
            ans = subseq;
            maxLen = subseq.length();
        }
    }
     
    cout << ans << endl;
}
 
int main()
{
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);
  
    return 0;
}


Java




import java.util.Arrays;
 
public class Main {
 
    public static void longestSubseqWithK(String str, int k) {
        int n = str.length();
        String ans = "";
        int maxLen = 0;
 
        // Generate all possible subsequences using bit manipulation
        for (int i=0; i<(1<<n); i++) {
            StringBuilder subseq = new StringBuilder();
            for (int j=0; j<n; j++) {
                if ((i&(1<<j)) != 0)
                    subseq.append(str.charAt(j));
            }
 
            // Count frequency of each character in the subsequence
            int[] freq = new int[26];
            Arrays.fill(freq, 0);
            for (int j=0; j<subseq.length(); j++) {
                char c = subseq.charAt(j);
                freq[c-'a']++;
            }
 
            // Check if each character appears at least k times
            boolean flag = true;
            for (int f : freq) {
                if (f > 0 && f < k) {
                    flag = false;
                    break;
                }
            }
 
            // Update answer if the subsequence satisfies the condition
            if (flag && subseq.length() > maxLen) {
                ans = subseq.toString();
                maxLen = subseq.length();
            }
        }
 
        System.out.println(ans);
    }
 
    public static void main(String[] args) {
        String str = "geeksforgeeks";
        int k = 2;
        longestSubseqWithK(str, k);
    }
}
// This code is contributed by Prajwal Kandekar


Python3




def longestSubseqWithK(str, k):
    n = len(str)
    ans = ""
    maxLen = 0
     
    # Generate all possible subsequences using bit manipulation
    for i in range(1<<n):
        subseq = ""
        for j in range(n):
            if i&(1<<j):
                subseq += str[j]
         
        # Count frequency of each character in the subsequence
        freq = [0]*26
        for c in subseq:
            freq[ord(c)-ord('a')] += 1
         
        # Check if each character appears at least k times
        flag = True
        for f in freq:
            if f > 0 and f < k:
                flag = False
                break
         
        # Update answer if the subsequence satisfies the condition
        if flag and len(subseq) > maxLen:
            ans = subseq
            maxLen = len(subseq)
     
    print(ans)
 
str = "geeksforgeeks"
k = 2
longestSubseqWithK(str, k)


C#




using System;
 
class Program
{
static void longestSubseqWithK(string str, int k)
{
int n = str.Length;
string ans = "";
int maxLen = 0;
      // Generate all possible subsequences using bit manipulation
    for (int i = 0; i < (1 << n); i++)
    {
        string subseq = "";
        for (int j = 0; j < n; j++)
        {
            if ((i & (1 << j)) != 0)
                subseq += str[j];
        }
 
        // Count frequency of each character in the subsequence
        int[] freq = new int[26];
        Array.Clear(freq, 0, freq.Length);
        foreach (char c in subseq)
            freq++;
 
        // Check if each character appears at least k times
        bool flag = true;
        foreach (int f in freq)
        {
            if (f > 0 && f < k)
            {
                flag = false;
                break;
            }
        }
 
        // Update answer if the subsequence satisfies the condition
        if (flag && subseq.Length > maxLen)
        {
            ans = subseq;
            maxLen = subseq.Length;
        }
    }
 
    Console.WriteLine(ans);
}
 
static void Main(string[] args)
{
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);
 
    Console.ReadLine();
}
}


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




// C++ program to Find longest subsequence where
//  every character appears at-least k times
#include<bits/stdc++.h>
using namespace std;
 
const int MAX_CHARS = 26;
 
void longestSubseqWithK(string str, int k)   
{
    int n = str.size();                  
 
    // Count frequencies of all characters
    int freq[MAX_CHARS] = {0};                   
    for (int i = 0 ; i < n; i++)   
        freq[str[i] - 'a']++;             
     
    // Traverse given string again and print
    // all those characters whose frequency
    // is more than or equal to k.
    for (int i = 0 ; i < n ; i++)  
        if (freq[str[i] - 'a'] >= k)              
            cout << str[i];     
}
 
// Driver code
int main() {
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);      
    return 0;
}


Java




// Java program to Find longest subsequence where
//  every character appears at-least k times
 
class GFG {
 
    static final int MAX_CHARS = 26;
 
    static void longestSubseqWithK(String str, int k) {
        int n = str.length();
 
        // Count frequencies of all characters
        int freq[] = new int[MAX_CHARS];
        for (int i = 0; i < n; i++) {
            freq[str.charAt(i) - 'a']++;
        }
 
        // Traverse given string again and print
        // all those characters whose frequency
        // is more than or equal to k.
        for (int i = 0; i < n; i++) {
            if (freq[str.charAt(i) - 'a'] >= k) {
                System.out.print(str.charAt(i));
            }
        }
    }
 
// Driver code
    static public void main(String[] args) {
        String str = "geeksforgeeks";
        int k = 2;
        longestSubseqWithK(str, k);
 
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to Find longest subsequence where
#  every character appears at-least k times
  
MAX_CHARS = 26
  
def longestSubseqWithK(s, k):   
 
    n = len(s)                 
  
    # Count frequencies of all characters
    freq = [0]*MAX_CHARS                
    for i in range(n): 
        freq[ord(s[i]) - ord('a')]+=1             
      
    # Traverse given string again and print
    # all those characters whose frequency
    # is more than or equal to k.
    for i in range(n ):
        if (freq[ord(s[i]) - ord('a')] >= k):              
            print(s[i],end="")
  
# Driver code
if __name__ == "__main__":
     
    s = "geeksforgeeks"
    k = 2
    longestSubseqWithK(s, k)


Javascript




<script>
 
// Javascript program to find longest subsequence
// where every character appears at-least k times
let MAX_CHARS = 26;
 
function longestSubseqWithK(str, k)
{
    let n = str.length;
 
    // Count frequencies of all characters
    let freq = new Array(MAX_CHARS);
    for(let i = 0; i < freq.length; i++)
    {
        freq[i] = 0
    }
     
    for(let i = 0; i < n; i++)
    {
        freq[str[i].charCodeAt(0) -
                'a'.charCodeAt(0)]++;
    }
 
    // Traverse given string again and print
    // all those characters whose frequency
    // is more than or equal to k.
    for(let i = 0; i < n; i++)
    {
        if (freq[str[i].charCodeAt(0) -
                    'a'.charCodeAt(0)] >= k)
        {
            document.write(str[i]);
        }
    }
}
 
// Driver code
let str = "geeksforgeeks";
let k = 2;
 
longestSubseqWithK(str, k);
 
// This code is contributed by avanitrachhadiya2155
     
</script>


C#




     
// C# program to Find longest subsequence where
//  every character appears at-least k times
using System;
public class GFG {
  
    static readonly int MAX_CHARS = 26;
  
    static void longestSubseqWithK(String str, int k) {
        int n = str.Length;
  
        // Count frequencies of all characters
        int []freq = new int[MAX_CHARS];
        for (int i = 0; i < n; i++) {
            freq[str[i]- 'a']++;
        }
  
        // Traverse given string again and print
        // all those characters whose frequency
        // is more than or equal to k.
        for (int i = 0; i < n; i++) {
            if (freq[str[i] - 'a'] >= k) {
                Console.Write(str[i]);
            }
        }
    }
  
// Driver code
    static public void Main() {
        String str = "geeksforgeeks";
        int k = 2;
        longestSubseqWithK(str, k);
  
    }
}
  
// This code is contributed by Rajput-Ji


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




// C++ program to Find longest subsequence where every
// character appears at-least k times
#include <bits/stdc++.h>
using namespace std;
 
void longestSubseqWithK(string str, int k)
{
    int n = str.size();
    map<char, int> mp;
 
    // Count frequencies of all characters
    for (int i = 0; i < n; i++) {
        char t = str[i];
        mp[t]++;
    }
 
    // Traverse given string again and print
    // all those characters whose frequency
    // is more than or equal to k.
    for (int i = 0; i < n; i++) {
        char t = str[i];
        if (mp[t] >= k) {
            cout << t;
        }
    }
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);
 
    return 0;
}
 
// This code is contributed by rakeshsahni


Java




/*package whatever //do not write package name here */
// Java program to Find longest subsequence where every
// character appears at-least k times
 
import java.io.*;
import java.util.HashMap;
 
class GFG {
 
    static void longestSubseqWithK(String str, int k)
    {
        int n = str.length();
        HashMap<Character, Integer> hm = new HashMap<>();
 
        // Count frequencies of all characters
        for (int i = 0; i < n; i++) {
            char c = str.charAt(i);
            if (hm.containsKey(c))
                hm.put(c, hm.get(c) + 1);
            else
                hm.put(c, 1);
        }
 
        // Traverse given string again and print
        // all those characters whose frequency
        // is more than or equal to k.
        for (int i = 0; i < n; i++) {
            char c = str.charAt(i);
            if (hm.get(c) >= k) {
                System.out.print(c);
            }
        }
    }
 
    // Driver code
    static public void main(String[] args)
    {
        String str = "geeksforgeeks";
        int k = 2;
        longestSubseqWithK(str, k);
    }
}
 
// This code is contributed by Chandan-Bedi


Python3




# Python3 program to Find longest subsequence where every
# character appears at-least k times
def longestSubseqWithK(Str, k):
  n = len(Str)
  hm = {}
 
  # Count frequencies of all characters
  for i in range(n):
    c = Str[i]
    if(c in hm):
        hm += 1
     
    else:
        hm = 1
 
  # Traverse given string again and print
  # all those characters whose frequency
  # is more than or equal to k.
  for i in range(n):
    c = Str[i]
    if (hm >= k):
      print(c,end="")
     
# Driver code
Str = "geeksforgeeks"
k = 2
longestSubseqWithK(Str, k)
 
# This code is contributed by shinjanpatra


Javascript




<script>
 
// JavaScript program to Find longest subsequence where every
// character appears at-least k times
function longestSubseqWithK(str, k)
{
  let n = str.length;
  let hm = new Map();
 
  // Count frequencies of all characters
  for (let i = 0; i < n; i++) {
    let c = str[i];
    if(hm.has(c)){
        hm.set(c,hm.get(c)+1);
    }
    else hm.set(c,1);
  }
 
  // Traverse given string again and print
  // all those characters whose frequency
  // is more than or equal to k.
  for (let i = 0; i < n; i++) {
    let c = str[i];
    if (hm.get(c) >= k) {
      document.write(c);
    }
  }
}
 
// Driver code
let str = "geeksforgeeks";
let k = 2;
longestSubseqWithK(str, k);
 
// This code is contributed by shinjanpatra
<script>


C#




// C# program to Find longest subsequence where every
// character appears at-least k times
using System;
using System.Collections;
 
class GFG {
 
  static void longestSubseqWithK(string str, int k)
  {
    int n = str.Length;
    Hashtable hm = new Hashtable();
 
    // Count frequencies of all characters
    for (int i = 0; i < n; i++) {
      char c = str[i];
      if (hm.ContainsKey(c)) {
        int old = (int)hm;
        hm.Remove(c);
        hm.Add(c, old + 1);
      }
      else
        hm.Add(c, 1);
    }
 
    // Traverse given string again and print
    // all those characters whose frequency
    // is more than or equal to k.
    for (int i = 0; i < n; i++) {
      char c = str[i];
      if ((int)hm >= k) {
        Console.Write(c);
      }
    }
  }
 
  // Driver code
  static public void Main(string[] args)
  {
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);
  }
}
 
// This code is contributed by karandeep1234


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. 

This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Last Updated : 24 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials