![]() |
VOOZH | about |
Given a string S of length N. Then your task is to find the count of substrings such that, the frequency of each digit in that substring must be less than the maximum digit of substring.
Input: S = 122321
Output: 13
Explanation: Below are some of those substrings:
- S[1, 2]: 12. Max element = 2, Frequency of 1 and 2 both is 1, Which is less than 2.
- S[1, 4]: 1223. Max element = 3, Frequencies of 1 and 2 and 3 are 1, 2 and 1 respectively. Which is less than 3.
- S[2]: 2. Max element = 2, Frequency of 2 is 1, Which is less than 2.
- S[2, 4]: 223. Max element = 3, Frequency of 2 and 3 both is 2 and 1, Which is less than 3.
- In the same way = {2, 23, 232, 2321, 3, 32, 321, 2, 21} are also other substrings satisfying the given conditions. So, there are 13 such substrings.
Input: S = 1231
Output: 8
Explanation: The 8 substrings, which satisfies the given condition are: {12, 123, 1231, 2, 23, 231, 3, 31}.
Approach:
As, the number of digits can only be 10. Starting from each index iterate for 72 times because substring of length greater than 72 can't satisfy the given condition, because maximum element can be 9 and each elements frequency can not exceed 8 in this case so in worst case it will be 8*9 length long valid substring ). Check how many subarrays are possible, where in each subarray frequency of each character in the substring is strictly less than the maximum digit of the substring.
Steps were taken to solve the problem:
Below is the implementation of the code:
13
Time Complexity: O(N)
Auxiliary Space: O(N)