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 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();
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count Substrings with all Unique Digits in Range [0, K] Given a string S of length N (1 <= N <= 107) and a positive integer K, where the string contains only numbers in the range [0, 9], the task is to determine the count of substrings that include at least one occurrence of all the unique digits within the specified range [0, K]. Example: Input: S
9 min read
Count of Substrings with at least K pairwise Distinct Characters having same Frequency Given a string S and an integer K, the task is to find the number of substrings which consists of at least K pairwise distinct characters having same frequency. Examples: Input: S = "abasa", K = 2 Output: 5 Explanation: The substrings in having 2 pairwise distinct characters with same frequency are
7 min read
Count number of substrings with numeric value greater than X Given a string 'S' (composed of digits) and an integer 'X", the task is to count all the sub-strings of 'S' that satisfy the following conditions: The sub-string must not begin with the digit '0'.And the numeric number it represents must be greater than 'X'. Note: Two ways of selecting a sub-string
5 min read
Distinct Substring frequency counter Given a string s of length N containing only lowercase English letters and an integer K, the task is to find all distinct substrings of S of length K, and for each substring, count the number of times it occurs in S. You need to return a list of all distinct substrings along with their frequency of
4 min read
Count numbers with same first and last digits Given an interval, the task is to count numbers that have the same first and last digits. For example, 1231 has the same first and last digits. Examples: Input : start = 7, end : 68 Output : 9 Number with same first and last digits are, 7 8 9 11 22 33 44 55 66. Input : start = 5, end : 40 Output : 8
9 min read
Check if frequency of each digit is less than the digit Given an integer n, the task is to check if frequency of each digit of the number is less than or equal to digit itself. Examples: Input : 51241 Output : False Input : 1425243 Output : True Naive Approach: Start from 0 and count the frequency for every digit upto 9, if at any place frequency is more
8 min read
Count of substrings that start and end with 1 in given Binary String Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
12 min read
Count of substrings whose Decimal equivalent is greater than or equal to K Given an integer K and a binary string S of length N, the task is to find out the number of substrings whose decimal equivalent is greater than or equal to K. Examples: Input: K = 3, S = "11100" Output: 8 Explanation: There are 8 such substring whose decimal equivalent is greater than or equal to 3,
12 min read
Count substrings with different first and last characters Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different. Examples: Input: S = "abcab"Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}. Input: S = "ab
10 min read
Number of substrings with equal character frequencies and fixed distance Given a string S and an integer K, the task is to count the number of substrings which have each character exactly K times and maximum distance between two same characters <= K. Examples: Input: S= " de", K = 2Output: 3Explanation: "abab", "ababcc" and "cc" are substrings having each character ex
10 min read