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
Count Substrings: Input "aaaba" → Output 10aaabaGroup 1: "aaa" (n=3)Group 2: "b" (n=1)Group 3: "a" (n=1)3*(3+1)/2 = 61*(1+1)/2 = 11*(1+1)/2 = 1Count all substrings with only one distinct letterTotal: 6 + 1 + 1 + 1 + 1 = 10
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
Asked in
Google 25 Facebook 20 Amazon 15
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen