![]() |
VOOZH | about |
Given a string S, a string T is considered good if following 2 conditions hold:
For example, if S = "aaabb" then T = "aab" is good because T is subsequence of S at indices 1,3,5 which is an arithmetic progression. The task is to determine any subsequence that is good string having highest occurrences in the string. Print the number of times that subsequence appears as a good string in the given string.
Examples:
Input: S = "aaabb"
Output: 6
Explanation: "ab" is the good strings with the highest number of occurrences. "ab" occurred 6 times at (1,4), (1,5), (2,4), (2,5), (3,4) and (3,5)Input: "abcde"
Output: 1
Explanation: "a" is the good string which occurred only once.
Observations:
We observe that if the good string that occurs the most times has length > 2, then there must exist one that occurs just as many times of length exactly 2. This is true because we can always just take the first 2 letters of the good string and still get the answer. Therefore, we only need to check strings of lengths 1 and 2.
Approach: The problem can be solved using the following approach:
The intuition is based on the properties of subsequences and arithmetic progressions. Here's the key idea:
- The problem asks for a good subsequence, which is defined as a subsequence where the indices form an arithmetic progression. This means that the characters in the subsequence are evenly spaced in the original string.
- Count the frequency of each character and each pair of characters in the string. we'll use two arrays, arr1 and arr2, to store these frequencies. arr1[c][/c] is the frequency of character c, and arr2[i][j] is the frequency of pairs of characters i and j where j appears after i in the string.
- Now, iterate over the string and for each character, updates the frequency of that character and all pairs that can be formed with that character. After that, finds the maximum frequency among all characters and all pairs of characters. This maximum frequency is the number of times the most frequent good subsequence appears in the string.
This approach will work because a good subsequence can be either a single character or a pair of characters. A single character is always a good subsequence, and a pair of characters is a good subsequence if and only if the two characters appear at indices that form an arithmetic progression. By counting the frequency of each character and each pair of characters, the code effectively counts the frequency of all possible good subsequences.
Steps to solve the problem:
Below is the implementation of the above approach:
6
Time Complexity: O(N), where N is the length of the input string S.
Auxiliary Space: O(1)