Count Complete Substrings - Problem
You have been given a string word and an integer k. Your task is to find all complete substrings within the word and count how many exist.
A substring is considered complete if it satisfies two strict conditions:
- Character Frequency: Each character in the substring must appear exactly
ktimes - Adjacent Character Constraint: Any two adjacent characters in the substring must have an alphabetical distance of at most 2 (e.g., 'a' and 'c' are valid neighbors, but 'a' and 'd' are not)
For example, if word = "aaabbbccc" and k = 3, the substring "aaabbb" would be complete because each character appears exactly 3 times and 'a' and 'b' are adjacent in the alphabet (distance = 1 โค 2).
Goal: Return the total number of complete substrings in the given word.
Input & Output
example_1.py โ Basic Complete Substring
$
Input:
word = "aaabbbccc", k = 3
โบ
Output:
1
๐ก Note:
The only complete substring is "aaabbbccc" itself. Each character (a, b, c) appears exactly 3 times, and the adjacency constraint is satisfied since |a-b| = 1 โค 2 and |b-c| = 1 โค 2.
example_2.py โ Multiple Valid Substrings
$
Input:
word = "aabbcc", k = 2
โบ
Output:
3
๐ก Note:
Three complete substrings exist: "aabb" (a appears 2 times, b appears 2 times), "bbcc" (b appears 2 times, c appears 2 times), and "aabbcc" (each character appears exactly 2 times).
example_3.py โ Adjacency Constraint Violation
$
Input:
word = "aaafff", k = 3
โบ
Output:
0
๐ก Note:
No complete substrings exist because |a-f| = 5 > 2, violating the adjacency constraint. Even though each character appears 3 times in the full string, they cannot form a valid complete substring.
Constraints
- 1 โค word.length โค 105
- 1 โค k โค word.length
- word consists only of lowercase English letters
- Adjacent characters in complete substrings must have alphabetical distance โค 2
Visualization
Tap to expand
Understanding the Visualization
1
Identify Segments
Split string where adjacency constraint breaks (|char_i - char_{i-1}| > 2)
2
Process Each Segment
Within each valid segment, use sliding window technique
3
Try All Character Counts
For 1 to 26 unique characters, maintain window of size uniqueChars ร k
4
Count Valid Windows
Track character frequencies and count when all chars appear exactly k times
Key Takeaway
๐ฏ Key Insight: By segmenting the string based on adjacency constraints and then applying sliding window within each valid segment, we achieve optimal O(n) time complexity while correctly handling both character frequency and adjacency requirements.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code