Given a string ( containing characters from ‘0’ to ‘9’) and two digits and . The task is to find the substring in the given string with maximum occurrences and containing a’s and b’s only. If there are two or more such substrings with same frequencies then print the lexicographically smallest. If there does not exists any such substring then print -1.
Input : str = "47", a = 4, b = 7 Output : 4 Input : str = "23", a = 4, b = 7 Output : -1
The idea is to observe that we need to find the substring with maximum number of occurrences. So, if we consider substrings that contains both a’s and b’s then the number of occurrences will be less than if we consider the substrings with single digits ‘a’ and ‘b’ individually.
So, the idea is to calculate the frequency of digits of ‘a’ and ‘b’ in the string and the one with maximum frequency will be the answer.
Note: If both digits have same frequency then the digit which is lexicographically smaller among ‘a’ and ‘b’ will be the answer.
Below is the implementation of the above approach:
- Swap all occurrences of two characters to get lexicographically smallest string
- Lexicographically smallest and largest substring of size k
- K-th lexicographically smallest unique substring of a given string
- Count occurrences of a substring recursively
- Check if string can be made lexicographically smaller by reversing any substring
- Lexicographically smallest rotated sequence | Set 2
- Construct lexicographically smallest palindrome
- Lexicographically smallest string of length N and sum K
- Lexicographically Smallest Topological Ordering
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Make a lexicographically smallest palindrome with minimal changes
- Lexicographically smallest permutation of a string with given subsequences
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest string obtained after concatenating array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.