Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Lexicographically largest subsequence such that every character occurs at least k times
Next article icon

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


Next Article
Lexicographically largest subsequence such that every character occurs at least k times

S

Sakshi_Tiwari
Improve
Article Tags :
  • DSA
  • Strings
  • frequency-counting
  • subsequence
Practice Tags :
  • Strings

Similar Reads

  • Longest subsequence where every character appears at-least k times
    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 = 2Output: geeksgeeksExplanation: Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb", k = 5O
    12 min read
  • Longest substring where all the characters appear at least K times | Set 3
    Given a string str and an integer K, the task is to find the length of the longest substring S such that every character in S appears at least K times. Examples: Input: str = “aabbba”, K = 3Output: 6Explanation: In substring "aabbba", each character repeats at least k times and its length is 6. Inpu
    12 min read
  • Count substrings with each character occurring at most k times
    Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2
    15+ min read
  • Longest subsequence with at least one character appearing in every string
    Given a string array arr[], the task is to find the longest subsequence of the array with at least one character appearing in all the strings. Note that all the strings contain only lowercase English alphabets.Examples: Input: str = {"ab", "bc", "de"} Output: 2 {"ab", "bc"} is the required sub-seque
    6 min read
  • Lexicographically largest subsequence such that every character occurs at least k times
    Given a string s and an integer k, the task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least k times. Examples: Input : s = "banana", k = 2.Output : "nn"Explanation: Possible subsequence where each character exists at least 2 times are:
    6 min read
  • Longest Subsequence with difference between characters equals to K
    Given a string S consisting of lowercase letters. Find the longest subsequence of S such that the difference between the maximum and minimum occurring characters in the subsequence is exactly K. Examples: Input: S = 'abcdeg' and K = 4Output: abcde Input: S = 'daaaabbbadddddeeee', K = 1Output: dddddd
    9 min read
  • Largest sub-string where all the characters appear at least K times
    Given a string str and an integer K, the task is to find the length of the longest sub-string S' such that every character in S' appears at least K times. Input: s = "xyxyyz", k = 2 Output: 5 "xyxyy" is the longest sub-string where every character appears at least twice.Input: s = "geeksforgeeks", k
    7 min read
  • Longest subsequence with different adjacent characters
    Given string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different. Examples:   Input: str = "ababa" Output: 5 Explanation: "ababa" is the subsequence satisfying the condition Input: str = "xxxxy" Output: 2 Explan
    11 min read
  • Longest subsequence whose average is less than K
    Given an array of N positive integers and Q queries consisting of an integer K, the task is to print the length of the longest subsequence whose average is less than K. Examples: Input: a[] = {1, 3, 2, 5, 4} Query1: K = 3 Query2: K = 5 Output: 4 5 Query1: The subsequence is: {1, 3, 2, 4} or {1, 3, 2
    7 min read
  • Longest subsequence such that no 3 consecutive characters are same
    Given a string of lowercase characters S, the task is to find longest subsequence of the string with no 3 consecutive identical characters.Examples: Input: S = "eedaaad"Output: eedaadExplanation: One occurrence of letter a is deleted. Input: xxxtxxxOutput: xxtxx Approach: The task can be solved by c
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences