VOOZH about

URL: https://www.geeksforgeeks.org/dsa/frequency-of-maximum-occurring-subsequence-in-given-string/

⇱ Frequency of maximum occurring subsequence in given string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Frequency of maximum occurring subsequence in given string

Last Updated : 12 Jul, 2025

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:

  • 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:


Output: 
3

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

Comment