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:
Length of the longest subsequence such that XOR of adjacent elements is equal to K
Next article icon

Find the length of the longest subsequence with first K alphabets having same frequency

Last Updated : 28 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str with uppercase characters and an integer K, the task is to find the length of the longest subsequence such that the frequency of the first K alphabet is the same.

Examples: 

Input: str = “ACAABCCAB”, K=3 
Output: 6 
Explanation: One of the possible subsequences is “ACABCB”.

Input: str = “ACAABCCAB”, K=4 
Output: 0 
Explanation: Since the string does not contain ‘D’, no such subsequence can be obtained.  

Approach: 
Traverse the string and find the least frequent of the first K alphabets. Once found, (frequency of that element) * K gives the desired result.
Below is the implementation of the above approach:

C++




// C++ program to find the longest
// subsequence with first K
// alphabets having same frequency
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the
// length of the longest
// subsequence with first K
// alphabets having same frequency
int lengthOfSubsequence(string str,
                            int K)
{
    // Map to store frequency
    // of all characters in
    // the string
    map<char,int> mp;
    for (char ch : str) {
        mp[ch]++;
    }
     
    // Variable to store the
    // frequency of the least
    // frequent of first K
    // alphabets
    int minimum = mp['A'];
    for (int i = 1; i < K; i++) {
        minimum = min(minimum,
                    mp[(char)(i + 'A')]);
    }
     
    return minimum * K;
}
 
int main()
{
    string str = "ACAABCCAB";
    int K = 3;
     
    cout << lengthOfSubsequence(str, K);
    return 0;
}
 
 

Java




// Java program to find the longest
// subsequence with first K alphabets
// having same frequency
import java.util.*;
 
class GFG{
 
// Function to return the
// length of the longest
// subsequence with first K
// alphabets having same frequency
static int lengthOfSubsequence(String str,
                            int K)
{
     
    // Map to store frequency
    // of all characters in
    // the string
    Map<Character, Integer> mp = new HashMap<>();
    for(char ch : str.toCharArray())
    {
        mp.put(ch, mp.getOrDefault(ch, 0) + 1);
    }
 
    // Variable to store the
    // frequency of the least
    // frequent of first K
    // alphabets
    int minimum = mp.get('A');
    for(int i = 1; i < K; i++)
    {
        minimum = Math.min(minimum,
                        mp.get((char)(i + 'A')));
    }
    return minimum * K;
}
 
// Driver code
public static void main(String[] args)
{
    String str = "ACAABCCAB";
    int K = 3;
     
    System.out.println(lengthOfSubsequence(str, K));
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program to find the longest
# subsequence with first K alphabets
# having same frequency
from collections import defaultdict
 
# Function to return the
# length of the longest
# subsequence with first K
# alphabets having same frequency
def lengthOfSubsequence(st, K):
 
    # Map to store frequency
    # of all characters in
    # the string
    mp = defaultdict(int)
    for ch in st:
        mp[ch] += 1
     
    # Variable to store the
    # frequency of the least
    # frequent of first K
    # alphabets
    minimum = mp['A']
     
    for i in range(1, K):
        minimum = min(minimum,
                    mp[chr(i + ord('A'))])
     
    return (minimum * K)
 
# Driver code
if __name__ == "__main__":
     
    st = "ACAABCCAB"
    K = 3
     
    print(lengthOfSubsequence(st, K))
 
# This code is contributed by chitranayal
 
 

C#




// C# program to find the longest
// subsequence with first K alphabets
// having same frequency
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the
// length of the longest
// subsequence with first K
// alphabets having same frequency
static int lengthOfSubsequence(string str,
                               int K)
{
     
    // Store frequency
    // of all characters in
    // the string
    Dictionary<char,
               int> mp = new Dictionary<char,
                                        int>();
     
    foreach(char ch in str.ToCharArray())
    {
        mp[ch] = mp.GetValueOrDefault(ch, 0) + 1;
    }
 
    // Variable to store the frequency
    // of the least frequent of first K
    // alphabets
    int minimum = mp['A'];
    for(int i = 1; i < K; i++)
    {
        minimum = Math.Min(minimum,
                           mp[(char)(i + 'A')]);
    }
    return minimum * K;
}
 
// Driver code
public static void Main(string[] args)
{
    string str = "ACAABCCAB";
    int K = 3;
     
    Console.Write(lengthOfSubsequence(str, K));
}
}
 
// This code is contributed by rutvik_56
 
 

Javascript




<script>
 
// Javascript program to find the longest
// subsequence with first K
// alphabets having same frequency
 
// Function to return the
// length of the longest
// subsequence with first K
// alphabets having same frequency
function lengthOfSubsequence(str, K)
{
    // Map to store frequency
    // of all characters in
    // the string
    var mp = new Map();
 
    str.split('').forEach(ch => {
        if(mp.has(ch))
            mp.set(ch, mp.get(ch)+1)
        else   
            mp.set(ch, 1)
    });
     
    // Variable to store the
    // frequency of the least
    // frequent of first K
    // alphabets
    var minimum = mp.get('A');
    for (var i = 1; i < K; i++) {
        minimum = Math.min(minimum,
                    mp.get(String.fromCharCode(i + 'A'.charCodeAt(0))));
    }
     
    return minimum * K;
}
 
var str = "ACAABCCAB";
var K = 3;
 
document.write( lengthOfSubsequence(str, K));
 
 
 
</script>
 
 
Output: 
6

 



Next Article
Length of the longest subsequence such that XOR of adjacent elements is equal to K

M

mridulkumar
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Strings
  • cpp-strings
  • subsequence
Practice Tags :
  • cpp-strings
  • Strings

Similar Reads

  • Find length of the longest non-intersecting anagram Subsequence
    Given a string S of length N, find the length of the two longest non-intersecting subsequences in S that are anagrams of each other. Input: S = "aaababcd"Output: 3Explanation: Index of characters in the 2 subsequences are: {0, 1, 3} = {a, a, b} {2, 4, 5} = {a, a, b} The above two subsequences of S a
    6 min read
  • Length of the longest subsequence such that XOR of adjacent elements is equal to K
    Given an array arr[] of N non-negative integers and an integer K, the idea is to find the length of the longest subsequence having Xor of adjacent elements equal to K. Examples: Input: N = 5, arr[] = {3, 2, 4, 3, 5}, K = 1Output: 3Explanation:All the subsequences having Xor of adjacent element equal
    13 min read
  • Longest Subsequence with same char as substrings and difference of frequency at most K
    Given a string S of length N containing small-case English alphabets and an integer K, the task is to find the maximum possible length of the subsequence of S such that: The frequency of each letter in the subsequence does not differ by more than K from the frequency of any other letter.For any lett
    7 min read
  • Longest subsequence with consecutive English alphabets
    Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets. Examples: Input: S = "acbdcfhg"Output: 3Explanation: String "abc" is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence
    6 min read
  • Length of longest subarray having frequency of every element equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subarray such that each element occurs K times. Examples: Input: arr[] = {3, 5, 2, 2, 4, 6, 4, 6, 5}, K = 2Output: 8Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has freque
    9 min read
  • Length of longest increasing subsequence in a string
    Given a string S, the task is to find the length of the longest increasing subsequence present in the given string. A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence. Examples: Input: S = "abcfgffs"Output: 6Explanation: Subsequence "abcfgs" is
    7 min read
  • Count of Substrings with at least K pairwise Distinct Characters having same Frequency
    Given a string S and an integer K, the task is to find the number of substrings which consists of at least K pairwise distinct characters having same frequency. Examples: Input: S = "abasa", K = 2 Output: 5 Explanation: The substrings in having 2 pairwise distinct characters with same frequency are
    7 min read
  • Length of the longest increasing subsequence which does not contain a given sequence as Subarray
    Given two arrays arr[] and arr1[] of lengths N and M respectively, the task is to find the longest increasing subsequence of array arr[] such that it does not contain array arr1[] as subarray. Examples: Input: arr[] = {5, 3, 9, 3, 4, 7}, arr1[] = {3, 3, 7}Output: 4Explanation: Required longest incre
    14 min read
  • Length of longest subsequence having absolute difference of all pairs divisible by K
    Given an array, arr[] of size N and an integer K, the task is to find the length of the longest subsequence from the given array such that the absolute difference of each pair in the subsequence is divisible by K. Examples: Input: arr[] = {10, 12, 16, 20, 32, 15}, K = 4 Output: 4 Explanation:The Lon
    6 min read
  • Find the length of the longest subarray with atmost K occurrences of the integer X
    Given two numbers K, X and an array arr[] containing N integers, the task is to find the length of the longest subarray such that it contains atmost 'K' occurrences of integer'X'.Examples: Input: K = 2, X = 2, arr[] = {1, 2, 2, 3, 4} Output: 5 Explanation: The longest sub-array is {1, 2, 2, 3, 4} wh
    9 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