#1876
Substrings of Size Three with Distinct Characters
EasyHash TableStringSliding WindowCountingSliding WindowHash Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a sliding window approach allows us to efficiently check each substring of length three without needing to extract and check each substring separately. This reduces the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter to zero and a set to track distinct characters.
- 2Step 2: Loop through the string while maintaining a sliding window of size 3.
- 3Step 3: For each new character added to the window, check if it is distinct from the previous two characters.
- 4Step 4: If the window has three distinct characters, increment the counter.
- 5Step 5: Move the window one character to the right and repeat until the end of the string.
solution.py6 lines
1def countGoodSubstrings(s):
2 count = 0
3 for i in range(len(s) - 2):
4 if len(set(s[i:i+3])) == 3:
5 count += 1
6 return countℹ
Complexity note: The time complexity is O(n) since we only make a single pass through the string. The space complexity is O(1) as we are not using additional data structures that grow with input size.
- 1A substring is only good if all characters are distinct.
- 2Using a set can help quickly determine if characters are distinct.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.