Open In App

Longest subsequence where each character occurs at least k times

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string 's' and an integer k, find other string 't' such that 't' is the largest subsequence of given string 's' and each character of 't' must occur at least k times in string s.

Examples : 

Input s = "geeksforgeeks" k = 2
Output geeksgeeks
Explanation 'g', 'e', 'k', and 's' appear twice or more, so the output is "geeksgeeks"

Input s = "baaabaacba" k = 3
Output baaabaaba
Explanation Characters 'b' and 'a' appear at least 3 times, so the result is "baaabaaba".

[Naive Approach] Generate All Subsequences - Exponential time

We can solve the problem by generating all subsequences of the string. For each subsequence, we check if every character appears at least k times. Among all valid subsequences, we keep track of the longest one.

[Efficient Approach] Using Frequency Counting - O(n) time and O(1) space

  • We use a counter array to store the frequency of each character in the string.
  • Then, iterate through the string, and for each character, check if its count is greater than or equal to k. If it is, include that character in the result.
C++
#include <iostream>
using namespace std;

#define MAX_CHAR 26

// Function to find the subsequence
string findSubsequence(string &str, int k)
{
    int count[MAX_CHAR] = { 0 };

    // Counting occurrences of all characters
    for (char c : str) 
        count[c - 'a']++;

    // Storing characters with count >= k
    string res;
    for (char c : str) 
        if (count[c - 'a'] >= k)
            res += c;    

    return res;
}

int main()
{
    string str = "geeksforgeeks";
    int k = 2;
    cout << findSubsequence(str, k);
    return 0;
}
Java
// Importing necessary libraries
import java.util.HashMap;
import java.util.Map;

public class Main {
    
    // Function to find the subsequence
    public static String findSubsequence(String str, int k) {
        int[] count = new int[26];

        // Counting occurrences of all characters
        for (char c : str.toCharArray())
            count[c - 'a']++;

        // Storing characters with count >= k
        StringBuilder res = new StringBuilder();
        for (char c : str.toCharArray())
            if (count[c - 'a'] >= k)
                res.append(c);

        return res.toString();
    }

    public static void main(String[] args) {
        String str = "geeksforgeeks";
        int k = 2;
        System.out.println(findSubsequence(str, k));
    }
}
Python
# Function to find the subsequence
def find_subsequence(s, k):
    count = [0] * 26

    # Counting occurrences of all characters
    for c in s:
        count[ord(c) - ord('a')] += 1

    # Storing characters with count >= k
    res = ''
    for c in s:
        if count[ord(c) - ord('a')] >= k:
            res += c

    return res

# Main function
if __name__ == '__main__':
    str = 'geeksforgeeks'
    k = 2
    print(find_subsequence(str, k))
C#
// Function to find the subsequence
using System;
using System.Collections.Generic;

class Program {
    public static string FindSubsequence(string str, int k) {
        int[] count = new int[26];

        // Counting occurrences of all characters
        foreach (char c in str)
            count[c - 'a']++;

        // Storing characters with count >= k
        string res = "";
        foreach (char c in str)
            if (count[c - 'a'] >= k)
                res += c;

        return res;
    }

    static void Main() {
        string str = "geeksforgeeks";
        int k = 2;
        Console.WriteLine(FindSubsequence(str, k));
    }
}
JavaScript
// Function to find the subsequence
function findSubsequence(str, k) {
    const count = new Array(26).fill(0);

    // Counting occurrences of all characters
    for (let c of str) 
        count[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;

    // Storing characters with count >= k
    let res = '';
    for (let c of str) 
        if (count[c.charCodeAt(0) - 'a'.charCodeAt(0)] >= k)
            res += c;

    return res;
}

// Main function
const str = 'geeksforgeeks';
const k = 2;
console.log(findSubsequence(str, k));

Output
geeksgeeks

Article Tags :
Practice Tags :

Similar Reads