Back to Sliding Window
Course Practice
Easy

Substrings of Size Three with Distinct Characters

LAB

Return the number of length-3 substrings with three distinct characters.

EXAMPLES

Example 1
Input
{
  "s": "xyzzaz"
}

Output
1

FUNCTION SHAPE

s: stringint
SOLUTION NOTE

Window: Counter(). Valid: len(freq) == 3 (because the substring has fixed length 3, if we have a counter of length 3, this means we have no repeated chars).

Reveal reference solution +
pythonREFERENCE
def countGoodSubstrings(self, s: str) -> int:
    freq = Counter()
    n = len(s)
    res = 0
    k = 3

    for i in range(n):
        freq[s[i]] += 1

        if i >= k - 1:
            if len(freq) == 3:  # no repeated chars
                res += 1
            freq[s[i-(k-1)]] -= 1
            if freq[s[i-(k-1)]] == 0:
                del freq[s[i-(k-1)]]

    return res
TimeO(n)
SpaceO(1)
Open on LeetCode
00:00
2 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.