Count Substrings with Only One Distinct Letter - Problem
Count Substrings with Only One Distinct Letter
Given a string
A substring is a contiguous sequence of characters within a string. For example, in the string
Goal: Return the count of all possible substrings that contain only one distinct character.
Example: For
Given a string
s, you need to find the total number of substrings where all characters in the substring are exactly the same.A substring is a contiguous sequence of characters within a string. For example, in the string
"aaabb", valid single-character substrings include "a", "aa", "aaa", "b", and "bb".Goal: Return the count of all possible substrings that contain only one distinct character.
Example: For
s = "aaaba", the answer is 8 because we can form: "a" (4 times), "aa" (2 times), "aaa" (1 time), and "b" (1 time). Input & Output
example_1.py โ Basic case with mixed characters
$
Input:
s = "aaaba"
โบ
Output:
8
๐ก Note:
The substrings with one distinct letter are: "a" (appears 4 times), "aa" (appears 2 times), "aaa" (appears 1 time), "b" (appears 1 time). Total: 4 + 2 + 1 + 1 = 8.
example_2.py โ All same characters
$
Input:
s = "aaaa"
โบ
Output:
10
๐ก Note:
With 4 consecutive 'a's, we get: "a" (4 times), "aa" (3 times), "aaa" (2 times), "aaaa" (1 time). Total: 4 + 3 + 2 + 1 = 10. This follows the formula n*(n+1)/2 = 4*5/2 = 10.
example_3.py โ Single character edge case
$
Input:
s = "a"
โบ
Output:
1
๐ก Note:
Only one possible substring: "a" itself, which contains exactly one distinct character.
Constraints
- 1 โค s.length โค 105
- s consists of only lowercase English letters
- String is guaranteed to be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Walk the Orchard
Move through the orchard identifying groups of same trees
2
Count Sections
For each group of n same trees, count n*(n+1)/2 continuous sections
3
Sum Results
Add up all section counts from different tree groups
Key Takeaway
๐ฏ Key Insight: Instead of checking every possible section individually, we group consecutive identical items and use the mathematical formula nร(n+1)/2 to instantly calculate how many continuous sections each group contributes.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code