VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subsequence-where-each-character-occurs-at-least-k-times/

⇱ Longest subsequence where each character occurs at least k times - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest subsequence where each character occurs at least k times

Last Updated : 20 Mar, 2025

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.

Output
geeksgeeks
Comment