Leetcode #1180: Count Substrings with Only One Distinct Letter
In this guide, we solve Leetcode #1180 Count Substrings with Only One Distinct Letter in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a string s, return the number of substrings that have only one distinct letter. Example 1: Input: s = "aaaba" Output: 8 Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: s = "aaaba"
Output: 8
Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
"aaa" occurs 1 time.
"aa" occurs 2 times.
"a" occurs 4 times.
"b" occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.
Python Solution
class Solution:
def countLetters(self, s: str) -> int:
n = len(s)
i = ans = 0
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
ans += (1 + j - i) * (j - i) // 2
i = j
return ans
Complexity
The time complexity is , where is the length of the string . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.