Open In App

Count Substrings with Frequencies Less than Maximum Digit

Last Updated : 31 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 Jth digit 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 increment Ans.
  • Return Ans.

Below is the implementation of the code:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to count such substrings
int CountStrings(string S)
{
 
    // Intialize n with size of string
    int N = S.size();
 
    // Variable to hold Count of substrings
    int ans = 0;
 
    // Iterating over string using loop
    for (int i = 0; i < N; i++) {
 
        // Vector intialisation of 10 digits
        vector<int> freq(10, 0);
 
        int maxNumber = 0;
        int maxFrequency = 0;
 
        // Iterate further for 82 times
        for (int j = i; j < min(i + 72, N); j++) {
 
            // Increase in Frequency
            freq[S[j] - '0']++;
 
            // Update the maximum digit
            maxNumber = max(maxNumber, S[j] - '0');
            maxFrequency
                = max(maxFrequency, freq[S[j] - '0']);
 
            // If freq is less than maximum digit
            if (maxNumber > maxFrequency)
 
                // Incrementing ans
                ans++;
        }
    }
 
    // Return the count of subarray
    return ans;
}
 
// Driver code
int main()
{
 
    string S = "123221";
 
    // Function call
    cout << CountStrings(S);
 
    return 0;
}


Java




import java.util.*;
 
public class Program {
 
    // Function to count such substrings
    static int countStrings(String S) {
        // Initialize n with the size of the string
        int N = S.length();
 
        // Variable to hold the count of substrings
        int ans = 0;
 
        // Iterating over the string using a loop
        for (int i = 0; i < N; i++) {
            // HashMap initialization of 10 digits
            HashMap<Character, Integer> freq = new HashMap<>();
 
            int maxNumber = 0;
            int maxFrequency = 0;
 
            // Iterate further for 72 times
            for (int j = i; j < Math.min(i + 72, N); j++) {
                // Increase in Frequency
                freq.put(S.charAt(j), freq.getOrDefault(S.charAt(j), 0) + 1);
 
                // Update the maximum digit
                maxNumber = Math.max(maxNumber, S.charAt(j) - '0');
                maxFrequency = Math.max(maxFrequency, freq.get(S.charAt(j)));
 
                // If freq is less than the maximum digit
                if (maxNumber > maxFrequency) {
                    // Incrementing ans
                    ans++;
                }
            }
        }
 
        // Return the count of the subarray
        return ans;
    }
 
    // Driver code
    public static void main(String[] args) {
        String S = "123221";
 
        // Function call
        System.out.println(countStrings(S));
    }
}


Python3




def count_strings(S):
    # Initialize n with the size of the string
    N = len(S)
 
    # Variable to hold the count of substrings
    ans = 0
 
    # Iterating over the string using a loop
    for i in range(N):
        # Vector initialization of 10 digits
        freq = [0] * 10
 
        max_number = 0
        max_frequency = 0
 
        # Iterate further for 72 times
        for j in range(i, min(i + 72, N)):
            # Increase in frequency
            freq[int(S[j])] += 1
 
            # Update the maximum digit
            max_number = max(max_number, int(S[j]))
            max_frequency = max(max_frequency, freq[int(S[j])])
 
            # If frequency is less than the maximum digit
            if max_number > max_frequency:
                # Incrementing ans
                ans += 1
 
    # Return the count of substrings
    return ans
 
# Driver code
if __name__ == "__main__":
    S = "123221"
 
    # Function call
    print(count_strings(S))


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to count such substrings
    static int CountStrings(string S)
    {
        // Initialize n with the size of the string
        int N = S.Length;
 
        // Variable to hold the count of substrings
        int ans = 0;
 
        // Iterating over the string using a loop
        for (int i = 0; i < N; i++)
        {
            // Dictionary initialization of 10 digits
            Dictionary<char, int> freq = new Dictionary<char, int>();
             
            int maxNumber = 0;
            int maxFrequency = 0;
 
            // Iterate further for 72 times
            for (int j = i; j < Math.Min(i + 72, N); j++)
            {
                // Increase in Frequency
                if (!freq.ContainsKey(S[j]))
                    freq[S[j]] = 0;
                freq[S[j]]++;
 
                // Update the maximum digit
                maxNumber = Math.Max(maxNumber, S[j] - '0');
                maxFrequency = Math.Max(maxFrequency, freq[S[j]]);
 
                // If freq is less than the maximum digit
                if (maxNumber > maxFrequency)
                {
                    // Incrementing ans
                    ans++;
                }
            }
        }
 
        // Return the count of the subarray
        return ans;
    }
 
    // Driver code
    static void Main()
    {
        string S = "123221";
 
        // Function call
        Console.WriteLine(CountStrings(S));
    }
}


Javascript




function GFG(S) {
    const N = S.length;
    // Variable to hold the count of substrings
    let ans = 0;
    // Iterating over the string using a loop
    for (let i = 0; i < N; i++) {
        // Array initialization for 10 digits
        const freq = Array(10).fill(0);
        let maxNumber = 0;
        let maxFrequency = 0;
        for (let j = i; j < Math.min(i + 72, N); j++) {
            // Increase in frequency
            freq[parseInt(S[j])]++;
            // Update the maximum digit
            maxNumber = Math.max(maxNumber, parseInt(S[j]));
            maxFrequency = Math.max(maxFrequency, freq[parseInt(S[j])]);
            if (maxNumber > maxFrequency) {
                ans++;
            }
        }
    }
    // Return the count of substrings
    return ans;
}
// Driver code
function main() {
    const S = "123221";
    // Function call
    console.log(GFG(S));
}
main();


Output

13








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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads