HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A substring of length three is good exactly when its three characters are pairwise different. Once you choose its starting index i, there is no information from another window that can change this decision: compare s[i] with s[i + 1], s[i + 2], and compare the last two characters.
The only valid starting indices are 0 through n - 3. Move the start one position at a time, inspect the three characters beginning there, and increase the answer when all three comparisons succeed. Consecutive windows overlap, but that does not make them the same occurrence; every starting index must be counted separately.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | There are exactly max(0, n - 2) possible starting positions, and each position performs three constant-time comparisons. Windows overlap, but each starting position is processed once, so no substring is rescanned in a nested loop. |
| Space | O(1) extra | The solution stores only n, i, and count; the input string is not copied and the required returned integer is output, not working memory. The bound does not degrade for any input shape because the window remains fixed at three characters. |
#include <string>
using namespace std;
class Solution {
public:
int countGoodSubstrings(string s) {
int n = s.size();
int count = 0;
for (int i = 0; i + 2 < n; ++i) {
if (s[i] != s[i + 1] &&
s[i] != s[i + 2] &&
s[i + 1] != s[i + 2]) {
++count;
}
}
return count;
}
};The loop condition is written as i + 2 < n because the rightmost character used by the window is s[i + 2]. The condition directly states that this character is valid, while still allowing the final window beginning at n - 3. The three comparisons are the complete definition of distinctness for exactly three characters, so no set or frequency table is needed.