Find the Substring with maximum frequency and containing only X and Y
Given a string S of length N consisting of numbers from(0-9) and also two numbers, one is even (say X)and one is odd (say Y), the task is to find the substring which occurs maximum time and only contains X or Y.
Note: If two substrings have the same frequency then return the lexicographically smaller one.
Input: N = 5, S =”48947″, X = ‘4’, Y = ‘9’
Explanation: Sub-string “4” occurring maximum number of times in “48947”.
Input: N = 8, S = “22772777”, X = ‘2’, Y = ‘7’
Naive Approach:- The basic approach to solve the problem is to check for different substrings of different lengths consisting of only given even and odd numbers.
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Efficient Approach: The problem can be solved efficiently with the help of the following observation:
Just check out the occurrence of given even and odd digit.
Print out the digit from given X and Y which one occurs maximum number of times.
If both occur same number of times the print lexicographically minimum one.
Reason: The reason why we are just checking out the occurrence of the only even and odd digit and not the occurrence of the substring of length greater than 1:
Considering string: “22772777”
In this example “227” and “22” are occurring 1 time each, “27” is occurring 2 times and similarly for other substrings. But the single digit substring “7” is occurring 5 times which is the maximum among all.
The reason is the substrings of any length formed by only the given X and Y contain them as single length substrings. So they obviously occurs more times than the other substrings.
That is why, checking for only the given odd and even number substring of length 1 is needed.
Follow the steps to solve the problem:
- Initializing two count variables to store the count of X and Y.
- Traverse the string and check:
- If the current character is even or odd and increase their respective counts.
- Compare both the counts and return the one with a greater count.
- If the count of both of them are same then return the lexicographically minimum one.
Below is the implementation for the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)