Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a string word and an integer k.
A substring s of word is complete if:
s occurs exactly k times.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.
Example 1:
Input: word = "igigee", k = 2 Output: 3 Explanation: The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: igigee, igigee, igigee.
Example 2:
Input: word = "aaabbbccc", k = 3 Output: 6 Explanation: The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc.
Constraints:
1 <= word.length <= 105word consists only of lowercase English letters.1 <= k <= word.lengthProblem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"igigee" 2
"aaabbbccc" 3
number-of-substrings-containing-all-three-characters)count-substrings-without-repeating-character)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2953: Count Complete Substrings
class Solution {
public int countCompleteSubstrings(String word, int k) {
int n = word.length();
int ans = 0;
for (int i = 0; i < n;) {
int j = i + 1;
while (j < n && Math.abs(word.charAt(j) - word.charAt(j - 1)) <= 2) {
++j;
}
ans += f(word.substring(i, j), k);
i = j;
}
return ans;
}
private int f(String s, int k) {
int m = s.length();
int ans = 0;
for (int i = 1; i <= 26 && i * k <= m; ++i) {
int l = i * k;
int[] cnt = new int[26];
for (int j = 0; j < l; ++j) {
++cnt[s.charAt(j) - 'a'];
}
Map<Integer, Integer> freq = new HashMap<>();
for (int x : cnt) {
if (x > 0) {
freq.merge(x, 1, Integer::sum);
}
}
if (freq.getOrDefault(k, 0) == i) {
++ans;
}
for (int j = l; j < m; ++j) {
int a = s.charAt(j) - 'a';
int b = s.charAt(j - l) - 'a';
freq.merge(cnt[a], -1, Integer::sum);
++cnt[a];
freq.merge(cnt[a], 1, Integer::sum);
freq.merge(cnt[b], -1, Integer::sum);
--cnt[b];
freq.merge(cnt[b], 1, Integer::sum);
if (freq.getOrDefault(k, 0) == i) {
++ans;
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #2953: Count Complete Substrings
func countCompleteSubstrings(word string, k int) (ans int) {
n := len(word)
f := func(s string) (ans int) {
m := len(s)
for i := 1; i <= 26 && i*k <= m; i++ {
l := i * k
cnt := [26]int{}
for j := 0; j < l; j++ {
cnt[int(s[j]-'a')]++
}
freq := map[int]int{}
for _, x := range cnt {
if x > 0 {
freq[x]++
}
}
if freq[k] == i {
ans++
}
for j := l; j < m; j++ {
a := int(s[j] - 'a')
b := int(s[j-l] - 'a')
freq[cnt[a]]--
cnt[a]++
freq[cnt[a]]++
freq[cnt[b]]--
cnt[b]--
freq[cnt[b]]++
if freq[k] == i {
ans++
}
}
}
return
}
for i := 0; i < n; {
j := i + 1
for j < n && abs(int(word[j])-int(word[j-1])) <= 2 {
j++
}
ans += f(word[i:j])
i = j
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #2953: Count Complete Substrings
class Solution:
def countCompleteSubstrings(self, word: str, k: int) -> int:
def f(s: str) -> int:
m = len(s)
ans = 0
for i in range(1, 27):
l = i * k
if l > m:
break
cnt = Counter(s[:l])
freq = Counter(cnt.values())
ans += freq[k] == i
for j in range(l, m):
freq[cnt[s[j]]] -= 1
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
freq[cnt[s[j - l]]] -= 1
cnt[s[j - l]] -= 1
freq[cnt[s[j - l]]] += 1
ans += freq[k] == i
return ans
n = len(word)
ans = i = 0
while i < n:
j = i + 1
while j < n and abs(ord(word[j]) - ord(word[j - 1])) <= 2:
j += 1
ans += f(word[i:j])
i = j
return ans
// Accepted solution for LeetCode #2953: Count Complete Substrings
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2953: Count Complete Substrings
// class Solution {
// public int countCompleteSubstrings(String word, int k) {
// int n = word.length();
// int ans = 0;
// for (int i = 0; i < n;) {
// int j = i + 1;
// while (j < n && Math.abs(word.charAt(j) - word.charAt(j - 1)) <= 2) {
// ++j;
// }
// ans += f(word.substring(i, j), k);
// i = j;
// }
// return ans;
// }
//
// private int f(String s, int k) {
// int m = s.length();
// int ans = 0;
// for (int i = 1; i <= 26 && i * k <= m; ++i) {
// int l = i * k;
// int[] cnt = new int[26];
// for (int j = 0; j < l; ++j) {
// ++cnt[s.charAt(j) - 'a'];
// }
// Map<Integer, Integer> freq = new HashMap<>();
// for (int x : cnt) {
// if (x > 0) {
// freq.merge(x, 1, Integer::sum);
// }
// }
// if (freq.getOrDefault(k, 0) == i) {
// ++ans;
// }
// for (int j = l; j < m; ++j) {
// int a = s.charAt(j) - 'a';
// int b = s.charAt(j - l) - 'a';
// freq.merge(cnt[a], -1, Integer::sum);
// ++cnt[a];
// freq.merge(cnt[a], 1, Integer::sum);
//
// freq.merge(cnt[b], -1, Integer::sum);
// --cnt[b];
// freq.merge(cnt[b], 1, Integer::sum);
// if (freq.getOrDefault(k, 0) == i) {
// ++ans;
// }
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2953: Count Complete Substrings
function countCompleteSubstrings(word: string, k: number): number {
const f = (s: string): number => {
const m = s.length;
let ans = 0;
for (let i = 1; i <= 26 && i * k <= m; i++) {
const l = i * k;
const cnt: number[] = new Array(26).fill(0);
for (let j = 0; j < l; j++) {
cnt[s.charCodeAt(j) - 'a'.charCodeAt(0)]++;
}
const freq: { [key: number]: number } = {};
for (const x of cnt) {
if (x > 0) {
freq[x] = (freq[x] || 0) + 1;
}
}
if (freq[k] === i) {
ans++;
}
for (let j = l; j < m; j++) {
const a = s.charCodeAt(j) - 'a'.charCodeAt(0);
const b = s.charCodeAt(j - l) - 'a'.charCodeAt(0);
freq[cnt[a]]--;
cnt[a]++;
freq[cnt[a]] = (freq[cnt[a]] || 0) + 1;
freq[cnt[b]]--;
cnt[b]--;
freq[cnt[b]] = (freq[cnt[b]] || 0) + 1;
if (freq[k] === i) {
ans++;
}
}
}
return ans;
};
let n = word.length;
let ans = 0;
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && Math.abs(word.charCodeAt(j) - word.charCodeAt(j - 1)) <= 2) {
j++;
}
ans += f(word.substring(i, j));
i = j;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.