Count Substrings with Only One Distinct Letter - Problem
Count Substrings with Only One Distinct Letter

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
๐ŸŽ Apple Orchard Counting MethodOrchard Row: Apple-Apple-Apple-Orange-Apple๐ŸŽ๐ŸŽ๐ŸŽ๐ŸŠ๐ŸŽGroup 1: 3 Apple TreesGroup 2: 1 Orange TreeGroup 3: 1 Apple TreeCounting Continuous Sections:๐ŸŽ Apple Group (3 trees): 3 ร— 4 รท 2 = 6 sectionsโ€ข Single tree sections: [๐ŸŽ], [๐ŸŽ], [๐ŸŽ] = 3โ€ข Two-tree sections: [๐ŸŽ๐ŸŽ], [๐ŸŽ๐ŸŽ] = 2โ€ข Three-tree sections: [๐ŸŽ๐ŸŽ๐ŸŽ] = 1๐ŸŠ Orange Group (1 tree): 1 ร— 2 รท 2 = 1 sectionโ€ข Single tree sections: [๐ŸŠ] = 1๐ŸŽ Apple Group (1 tree): 1 ร— 2 รท 2 = 1 sectionโ€ข Single tree sections: [๐ŸŽ] = 1Total Continuous Sections: 6 + 1 + 1 = 8
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.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.8K Views
Medium Frequency
~15 min Avg. Time
1.5K 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