VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-substrings-with-frequencies-less-than-maximum-digit/

⇱ Count Substrings with Frequencies Less than Maximum Digit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Substrings with Frequencies Less than Maximum Digit

Last Updated : 31 Dec, 2023

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.

Examples:

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:

  • Create a variable let say Ans to store the count of substrings.
  • Run a loop for i = 0 to i < N and follow below mentioned conditions under the scope of loop:
    • Create a vector let say Freq of length 10.
    • Create two variables let say MaxNumber and MaxFrequency and initialize both to 0.
    • Run a loop for j = i to j < Min(i+72, N) and follow below mentioned steps under the scope of loop:
      • Increment the frequency of Jthdigit of S in vector.
      • Update MaxNumber with max(maxNumber, S[j] - '0')
      • Update MaxFrequency with max(maxFrequency, freq[S[j] - '0'])
      • if (MaxNumber > MaxFrequency), then incrementAns.
  • Return Ans.

Below is the implementation of the code:


Output
13

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment