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 INPUT word = "aaabbbccc" a a a b b b c c c 0 1 2 3 4 5 6 7 8 k = 3 len = 9 Complete Substring Rules: 1. Each char occurs exactly k times 2. Adjacent chars differ by at most 2 (in alphabet position) Alphabet positions: a=0, b=1, c=2, d=3... |a-b|=1, |b-c|=1, |a-c|=2 All valid (diff <= 2) ALGORITHM STEPS 1 Fixed Length Windows For m unique chars: len = m * k Try m = 1,2,3... (max 26) 2 Sliding Window Slide window of size m*k Track char frequencies 3 Check Adjacency Split at invalid pairs (diff > 2 breaks window) 4 Validate & Count All chars occur exactly k times Increment count if valid For k=3: m=1: len=3 --> "aaa","bbb","ccc" m=2: len=6 --> no valid m=3: len=9 --> "aaabbbccc" (but need exact k each) FINAL RESULT Complete Substrings Found: "aaa" a appears 3 times [OK] OK "bbb" b appears 3 times [OK] OK "ccc" c appears 3 times [OK] OK "aaabbbccc" (m=3, len=9) Each char k=3: Valid but counted above OUTPUT 3 Key Insight: Since each character must occur exactly k times, valid substrings have fixed lengths: m * k where m is the number of unique characters (1 to 26). Use sliding window for each possible length and check adjacency constraint. Time Complexity: O(26 * n) = O(n) where n is string length. Split segments at invalid adjacent pairs. TutorialsPoint - Count Complete Substrings | Optimal Solution
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