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: 8
💡 Note: Groups: "aaa"→6 substrings, "b"→1 substring, "a"→1 substring. Total: 6+1+1 = 8
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 with Only One Distinct Letter INPUT String s = "aaaba" a i=0 a i=1 a i=2 b i=3 a i=4 Consecutive Groups: "aaa" "b" "a" len=3 len=1 len=1 All Valid Substrings: "a","a","a","aa","aa","aaa" "b", "a" 6 + 1 + 1 substrings ALGORITHM STEPS 1 Find Groups Group consecutive same chars 2 Count Formula n*(n+1)/2 substrings per group 3 Apply to Each Calculate for all groups 4 Sum Results Add all group counts Calculations: "aaa": 3*(3+1)/2 = 6 "b": 1*(1+1)/2 = 1 "a": 1*(1+1)/2 = 1 Total: 6 + 1 + 1 = 10 FINAL RESULT Output: 10 Substring Breakdown: Group "aaa" (6 substrings): a, a, a, aa, aa, aaa Group "b" (1 substring): b Group "a" (1 substring): a OK - Answer: 10 Key Insight: For a group of n consecutive identical characters, the number of substrings is n*(n+1)/2. This is because we can choose any starting and ending point: 1 + 2 + 3 + ... + n = n*(n+1)/2. Time Complexity: O(n) | Space Complexity: O(1) -- Single pass through the string! TutorialsPoint - Count Substrings with Only One Distinct Letter | Mathematical Optimization Approach
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