Count Substrings with Only One Distinct Letter - Problem
Given a string s, return the number of substrings that have only one distinct letter.
A substring is a contiguous sequence of characters within a string. For example, in the string "aaaba", the substrings "aaa", "aa", and "a" all have only one distinct letter, but "ab" does not.
Input & Output
Example 1 — Mixed Characters
$
Input:
s = "aaaba"
›
Output:
10
💡 Note:
Groups: "aaa"→6 substrings, "b"→1 substring, "a"→1 substring. Total: 6+1+1+1+1 = 10
Example 2 — All Same
$
Input:
s = "aaaa"
›
Output:
10
💡 Note:
One group of 4 chars: 4*(4+1)/2 = 10 substrings ("a", "aa", "aaa", "aaaa", "a", "aa", "aaa", "a", "aa", "a")
Example 3 — All Different
$
Input:
s = "abc"
›
Output:
3
💡 Note:
Each character forms its own group of length 1: 1*(1+1)/2 = 1 each. Total: 1+1+1 = 3
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Parse string into character groups
2
Count Groups
Apply n*(n+1)/2 formula to each group
3
Sum Results
Total count of valid substrings
Key Takeaway
🎯 Key Insight: Group consecutive identical characters and use the formula n*(n+1)/2 for efficient counting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code