Frequency of maximum occurring subsequence in given string

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:
Explanation: 
For “aba”, subsequence “ab” occurs maximum times in subsequence ‘ab’ and ‘aba’.

Input: s = “acbab” 
Output:
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:

  1. For length 1 count the frequency of each alphabet in the string.
  2. 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).
  3. 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).



  4. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 frequnecy of each 
    // english lowercase character 
    ll freq[26]; 
  
    // dp[i][j] stores the count of 
    // subsequnce with 'a' + i 
    // and 'a' + j character 
    ll dp[26][26]; 
  
    memset(freq, 0, sizeof freq); 
  
    // Intialize 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; 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
class GFG{
  
// Function to find the frequency
static int findCount(String s)
{
      
    // freq stores frequnecy of each
    // english lowercase character
    int []freq = new int[26];
  
    // dp[i][j] stores the count of
    // subsequnce 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import numpy
  
# Function to find the frequency 
def findCount(s):
  
    # freq stores frequnecy of each 
    # english lowercase character 
    freq = [0] * 26
  
    # dp[i][j] stores the count of 
    # subsequnce 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
  
class GFG{
  
// Function to find the frequency
static int findCount(String s)
{
      
    // freq stores frequnecy of each
    // english lowercase character
    int []freq = new int[26];
  
    // dp[i,j] stores the count of
    // subsequnce 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

chevron_right


Output: 

3

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.