Substrings of Size Three with Distinct Characters

The problem is asking us to find the number of substrings of length 3 from the given string that have all distinct characters.

We can use a sliding window approach to solve this problem.

Here is a Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def countGoodSubstrings(self, s: str) -> int:
        count = 0
        for i in range(len(s) - 2):
            # Get the substring of length 3
            substring = s[i:i+3]

            # Check if all the characters are unique
            if len(set(substring)) == 3:
                count += 1

        return count

We loop over the string from index 0 to len(s) - 2. For each index i, we extract a substring of length 3. We then check whether all characters in the substring are unique by converting the substring to a set and checking if the length of the set is 3 (since a set in Python only contains unique elements). If all characters are unique, we increment the count.

This solution works because it checks all possible substrings of length 3 in the string, and for each substring, it checks whether all characters are unique, which is exactly what the problem asks us to do. The time complexity is O(n), where n is the length of the string.

Q&A

Do this question after doing the above question: “Longest Substring Without Repeating Characters”