Substrings of Size Three with Distinct Characters
A string is good if there are no repeated characters. Given a string s, return the number of good substrings of length three in s. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. Slide a fixed length window of length 3 across the string and check whether all three characters inside are different.
Constraints
- 1 ≤ s.length ≤ 100
- s consists of lowercase English letters.
Example
s = "xyzzaz"1Explanation "xyz" is the only good substring of length three — the rest all repeat a character.
Check each window of size 3 for distinct characters
Window "xyz": x, y, z are all different — good substring. count = 1.
What happens in this step
window = "xyz" [0, 2] s[0]=x, s[1]=y, s[2]=z — all three different Good substring — count = 1.
Steps to visualize
- Place a window of length 3 on the first three characters.
- Check whether all three characters inside are different.
- If they are, count it as a good substring.
- Slide the window one step right and check again.
- Continue until the window reaches the end of the string.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Window "xyz": x, y, z are all different — good substring. count = 1.
What happens in this step
window = "xyz" [0, 2] s[0]=x, s[1]=y, s[2]=z — all three different Good substring — count = 1.
Solution
function countGoodSubstrings(s) {
if (s.length < 3) {
return 0;
}
let count = 0;
for (let left = 0; left + 2 < s.length; left++) {
const a = s[left];
const b = s[left + 1];
const c = s[left + 2];
if (a !== b && b !== c && a !== c) {
count++;
}
}
return count;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
s = "xyzzaz" | 1 | example from the docstring |
s = "ab" | 0 | string shorter than 3: no substrings of length 3 exist |
s = "abc" | 1 | smallest valid input: exactly one good substring |
s = "aaa" | 0 | smallest valid input: no distinct characters |
s = "abcabc" | 4 | every substring of length 3 qualifies |
s = "aabbcc" | 0 | no substrings qualify |
s = "aababcabc" | 4 | larger, hand-verified case |