Count Complete Substrings - Problem

You are given a string word and an integer k.

A substring s of word is complete if:

  • Each character in s occurs exactly k times.
  • The difference between two adjacent characters is at most 2. That is, for any two adjacent characters c1 and c2 in s, the absolute difference in their positions in the alphabet is at most 2.

Return the number of complete substrings of word.

A substring is a non-empty contiguous sequence of characters in a string.

Input & Output

Example 1 — Basic Case
$ Input: word = "aaabbbccc", k = 3
Output: 3
💡 Note: Complete substrings: "aaabbb" (a:3, b:3), "bbbccc" (b:3, c:3), "aaabbbccc" (a:3, b:3, c:3). All satisfy adjacency rule since |a-b|=1≤2 and |b-c|=1≤2.
Example 2 — No Valid Substrings
$ Input: word = "aaabbbccc", k = 2
Output: 0
💡 Note: No substring has each character appearing exactly 2 times. The string has 3 of each character, which doesn't match k=2.
Example 3 — Adjacency Violation
$ Input: word = "aaafff", k = 3
Output: 0
💡 Note: Although "aaa" and "fff" individually have characters appearing 3 times, |a-f|=5>2 violates adjacency rule, so no complete substrings exist.

Constraints

  • 1 ≤ word.length ≤ 1000
  • 1 ≤ k ≤ word.length
  • word consists only of lowercase English letters

Visualization

Tap to expand
Count Complete Substrings: "aaabbbccc" (k=3)aaabbbccca: 3 timesb: 3 timesc: 3 times"aaabbb" ✓"bbbccc" ✓"aaabbbccc" ✓Adjacency: |a-b|=1≤2 ✓, |b-c|=1≤2 ✓Complete Substrings Found: 3
Understanding the Visualization
1
Input
String "aaabbbccc" and k=3
2
Check Constraints
Find substrings where each character appears exactly k times and adjacency rule holds
3
Output
Count of valid complete substrings: 3
Key Takeaway
🎯 Key Insight: Split string by adjacency violations, then use sliding window to efficiently count substrings with exact character frequencies
Asked in
Google 15 Microsoft 12 Amazon 10
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen