You are given a string s
consisting of lowercase English letters. A substring is a contiguous sequence of characters within the string. We want to count the number of substrings of size three with distinct characters.
Example:
s = "xyzzaz"
Example:
s = "aababcabc"
s
?Here’s how you can implement the solution in Python:
def countGoodSubstrings(s: str) -> int:
count = 0
for i in range(len(s) - 2):
substr = s[i:i+3]
if len(set(substr)) == 3:
count += 1
return count
n - 2
times (where n
is the length of the string), and on each iteration, creating the substring and checking its characters for uniqueness takes a constant time (since we are handling substrings of a fixed length, 3).n
is the length of the string s
.This approach ensures that we efficiently count the number of valid substrings of length 3 with distinct characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?