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 DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Substring of length K having maximum frequency in the given string
Next article icon

Frequency of maximum occurring subsequence in given string

Last Updated : 04 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str of lowercase English alphabets, our task is to find the frequency of occurrence a subsequence of the string which occurs the maximum times.

Examples:

Input: s = “aba” 
Output: 2 
Explanation: 
For “aba”, subsequence “ab” occurs maximum times in subsequence ‘ab’ and ‘aba’.

Input: s = “acbab” 
Output: 3 
Explanation: 
For “acbab”, “ab” occurs 3 times which is the maximum.

Approach: The problem can be solved using Dynamic Programming. To solve the problem mentioned above the key observation is that the resultant subsequence will be of length 1 or 2 because frequency of any subsequence of length > 2 will be lower than the subsequence of length 1 or 2 as they are also present in higher length subsequences. So we need to check for the subsequence of length 1 or 2 only. Below are the steps:

  • For length 1 count the frequency of each alphabet in the string.
  • For length 2 form a 2D array dp[26][26], where dp[i][j] tells frequency of string of char(‘a’ + i) + char(‘a’ + j).
  • The recurrence relation is used in the step 2 is given by:

 dp[i][j] = dp[i][j] + freq[i] 
where, 
freq[i] = frequency of character char(‘a’ + i) 
dp[i][j] = frequency of string formed by current_character + char(‘a’ + i).

  • The maximum of frequency array and array dp[][] gives the maximum count of any subsequence in the given string.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#define ll long long
using namespace std;
 
// Function to find the frequency
ll findCount(string s)
{
    // freq stores frequency of each
    // english lowercase character
    ll freq[26];
 
    // dp[i][j] stores the count of
    // subsequence with 'a' + i
    // and 'a' + j character
    ll dp[26][26];
 
    memset(freq, 0, sizeof freq);
 
    // Initialize dp to 0
    memset(dp, 0, sizeof dp);
 
    for (int i = 0; i < s.size(); ++i) {
 
        for (int j = 0; j < 26; j++) {
 
            // Increment the count of
            // subsequence j and s[i]
            dp[j][s[i] - 'a'] += freq[j];
        }
 
        // Update the frequency array
        freq[s[i] - 'a']++;
    }
 
    ll ans = 0;
 
    // For 1 length subsequence
    for (int i = 0; i < 26; i++)
        ans = max(freq[i], ans);
 
    // For 2 length subsequence
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < 26; j++) {
 
            ans = max(dp[i][j], ans);
        }
    }
 
    // Return the final result
    return ans;
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "acbab";
 
    // Function Call
    cout << findCount(str);
 
    return 0;
}
 
 

Java




// Java program for the above approach
class GFG{
 
// Function to find the frequency
static int findCount(String s)
{
     
    // freq stores frequency of each
    // english lowercase character
    int []freq = new int[26];
 
    // dp[i][j] stores the count of
    // subsequence with 'a' + i
    // and 'a' + j character
    int [][]dp = new int[26][26];
 
    for(int i = 0; i < s.length(); ++i)
    {
        for(int j = 0; j < 26; j++)
        {
 
            // Increment the count of
            // subsequence j and s[i]
            dp[j][s.charAt(i) - 'a'] += freq[j];
        }
 
        // Update the frequency array
        freq[s.charAt(i) - 'a']++;
    }
 
    int ans = 0;
 
    // For 1 length subsequence
    for(int i = 0; i < 26; i++)
        ans = Math.max(freq[i], ans);
 
    // For 2 length subsequence
    for(int i = 0; i < 26; i++)
    {
        for(int j = 0; j < 26; j++)
        {
            ans = Math.max(dp[i][j], ans);
        }
    }
 
    // Return the final result
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String str
    String str = "acbab";
 
    // Function call
    System.out.print(findCount(str));
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 program for the above approach
import numpy
 
# Function to find the frequency
def findCount(s):
 
    # freq stores frequency of each
    # english lowercase character
    freq = [0] * 26
 
    # dp[i][j] stores the count of
    # subsequence with 'a' + i
    # and 'a' + j character
    dp = [[0] * 26] * 26
     
    freq = numpy.zeros(26)
    dp = numpy.zeros([26, 26])
 
    for i in range(0, len(s)):
        for j in range(26):
 
            # Increment the count of
            # subsequence j and s[i]
            dp[j][ord(s[i]) - ord('a')] += freq[j]
         
        # Update the frequency array
        freq[ord(s[i]) - ord('a')] += 1
 
    ans = 0
 
    # For 1 length subsequence
    for i in range(26):
        ans = max(freq[i], ans)
         
    # For 2 length subsequence
    for i in range(0, 26):
        for j in range(0, 26):
            ans = max(dp[i][j], ans)
     
    # Return the final result
    return int(ans)
 
# Driver Code
 
# Given string str
str = "acbab"
 
# Function call
print(findCount(str))
 
# This code is contributed by sanjoy_62
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the frequency
static int findCount(String s)
{
     
    // freq stores frequency of each
    // english lowercase character
    int []freq = new int[26];
 
    // dp[i,j] stores the count of
    // subsequence with 'a' + i
    // and 'a' + j character
    int [,]dp = new int[26, 26];
 
    for(int i = 0; i < s.Length; ++i)
    {
        for(int j = 0; j < 26; j++)
        {
 
            // Increment the count of
            // subsequence j and s[i]
            dp[j, s[i] - 'a'] += freq[j];
        }
 
        // Update the frequency array
        freq[s[i] - 'a']++;
    }
 
    int ans = 0;
 
    // For 1 length subsequence
    for(int i = 0; i < 26; i++)
        ans = Math.Max(freq[i], ans);
 
    // For 2 length subsequence
    for(int i = 0; i < 26; i++)
    {
        for(int j = 0; j < 26; j++)
        {
            ans = Math.Max(dp[i, j], ans);
        }
    }
 
    // Return the readonly result
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String str
    String str = "acbab";
 
    // Function call
    Console.Write(findCount(str));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the frequency
function findCount(s)
{
    // freq stores frequency of each
    // english lowercase character
    var freq = Array(26).fill(0);
 
    // dp[i][j] stores the count of
    // subsequence with 'a' + i
    // and 'a' + j character
    var dp = Array.from(Array(26), ()=>Array(26).fill(0));
 
    for (var i = 0; i < s.length; ++i) {
 
        for (var j = 0; j < 26; j++) {
 
            // Increment the count of
            // subsequence j and s[i]
            dp[j][s[i].charCodeAt(0) -
            'a'.charCodeAt(0)] += freq[j];
        }
 
        // Update the frequency array
        freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }
 
    var ans = 0;
 
    // For 1 length subsequence
    for (var i = 0; i < 26; i++)
        ans = Math.max(freq[i], ans);
 
    // For 2 length subsequence
    for (var i = 0; i < 26; i++) {
        for (var j = 0; j < 26; j++) {
 
            ans = Math.max(dp[i][j], ans);
        }
    }
 
    // Return the final result
    return ans;
}
 
// Driver Code
 
// Given string str
var str = "acbab";
 
// Function Call
document.write( findCount(str));
 
</script>
 
 
Output: 
3

Time Complexity: O(26*N), where N is the length of the given string.
Auxiliary Space: O(M), where M = 26*26



Next Article
Substring of length K having maximum frequency in the given string
author
kuwal786
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • DSA
  • Dynamic Programming
  • Greedy
  • Searching
  • Strings
  • frequency-counting
  • subsequence
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Greedy
  • Searching
  • Strings

Similar Reads

  • Substring of length K having maximum frequency in the given string
    Given a string str, the task is to find the substring of length K which occurs the maximum number of times. If more than one string occurs maximum number of times, then print the lexicographically smallest substring. Examples: Input: str = "bbbbbaaaaabbabababa", K = 5Output: ababaExplanation:The sub
    14 min read
  • Find number of times a string occurs as a subsequence in given string
    Given two strings, find the number of times the second string occurs in the first string, whether continuous or discontinuous. Examples: Input: string a = "GeeksforGeeks"string b = "Gks"Output: 4Explanation: The four strings are - (Check characters marked in bold)GeeksforGeeksGeeksforGeeksGeeksforGe
    15+ min read
  • Maximum consecutive occurrences of a string in another given string
    Given two strings str1 and str2, the task is to count the maximum consecutive occurrences of the string str2 in the string str1. Examples: Input: str1 = “abababcba”, str2 = “ba” Output: 2 Explanation: String str2 occurs consecutively in the substring { str[1], ..., str[4] }. Therefore, the maximum c
    7 min read
  • Count subsequence of length three in a given string
    Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string. Examples : Input : string = "GFGFGYSYIOIWIN", subsequence = "GFG" Output : 4 Explanation : There are 4 such subsequences as shown: GFGFGYSYIOIWIN GFGFGYSYIOIWIN GFGFGYSYI
    15 min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Maximum Occurrence in a Given Range
    Given an array of n integers in non-decreasing order. Find the number of occurrences of the most frequent value within a given range. Examples: Input : arr[] = {-5, -5, 2, 2, 2, 2, 3, 7, 7, 7} Query 1: start = 0, end = 9 Query 2: start = 4, end = 9 Output : 4 3 Explanation: Query 1: '2' occurred the
    15+ min read
  • Maximum length prefix of one string that occurs as subsequence in another
    Given two strings s and t. The task is to find maximum length of some prefix of the string S which occur in string t as subsequence. Examples : Input : s = "digger" t = "biggerdiagram" Output : 3 digger biggerdiagram Prefix "dig" of s is longest subsequence in t. Input : s = "geeksforgeeks" t = "agb
    5 min read
  • Maximum length substring with highest frequency in a string
    Given a string. The task is to find the maximum occurred substring with a maximum length. These occurrences can overlap. Examples: Input: str = "abab" Output: ab "a", "b", "ab" are occur 2 times. But, "ab" has maximum length Input: str = "abcd" Output: a Approach: The idea is to store the frequency
    5 min read
  • Count of maximum occurring subsequence using only those characters whose indices are in GP
    Given a string S, the task is to find the count of maximum occurring subsequence P from S using only those characters whose indexes are in Geometric Progression.Note: Consider 1-based indexing in S. Examples : Input: S = "ddee"Output: 4Explanation: If we take P = "de", then P occurs 4 times in S. {
    7 min read
  • Maximum repeated frequency of characters in a given string
    Given a string S, the task is to find the count of maximum repeated frequency of characters in the given string S.Examples: Input: S = "geeksgeeks" Output: Frequency 2 is repeated 3 times Explanation: Frequency of characters in the given string - {"g": 2, "e": 4, "k": 2, "s": 2} The frequency 2 is r
    6 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