Given an input string contains letters from 'a' to 'g'
Count how many substrings are there in the input string such that frequency of any character inside the substring is not more than the number of distinct characters present in the substring.
Example productSeq="abaa" Output = 8
Explanation: valid combinations are:
a
b
a
a
ab
ba
aba
baa
constraints:
1 <= input string length <= 10^5
characters in input string are in range a,b,c,d,e,g
Here is my code:
import java.util.HashMap;
public class Main {
public static int solve(String str) {
int n = str.length();
int validSubstrings = 0;
// Iterate over all possible starting points
for (int start = 0; start < n; start++) {
HashMap<Character, Integer> charCount = new HashMap<>();
int distinctChars = 0;
// Extend substring from 'start' to 'end'
for (int end = start; end < n; end++) {
char c = str.charAt(end);
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
// If this is the first occurrence of 'c', increase distinct count
if (charCount.get(c) == 1) {
distinctChars++;
}
// Check if the substring is valid
if (isValid(charCount, distinctChars)) {
validSubstrings++;
}
}
}
return validSubstrings;
}
// Function to check if a substring is valid
private static boolean isValid(HashMap<Character, Integer> charCount, int distinctChars) {
for (int count : charCount.values()) {
if (count > distinctChars) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(solve("abaa")); // Output: 8
System.out.println(solve("abab")); // Output: 10
System.out.println(solve("aacd")); // Output: 9
}
}
My code works fine when input string length is small. I am looking for better approach to solve this in less time complexity.