Count Substrings Starting and Ending with Given Character — Medium Problem & Solution
Return the number of substrings of s that both start and end with the character c. A single occurrence of c counts as a substring of length one.
- Difficulty: Medium
- Topics: Strings, Math, Counting
- Asked at: Amazon, Google, Oracle
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Return the number of substrings of s that both start and end with the character c. A single occurrence of c counts as a substring of length one.
Example 1
Input: s = "codekairo", c = "o"
Output: 3
Explanation: The two `o`s give `o`, `o` and `odekairo`.
Example 2
Input: s = "abada", c = "a"
Output: 6
Explanation: Three `a`s give 3 + 2 + 1 = 6 substrings.
Example 3
Input: s = "zzz", c = "z"
Output: 6
Constraints
1 <= s.length <= 10^4s and c consist only of lowercase English letters.
How to solve Count Substrings Starting and Ending with Given Character
Count the occurrences of c. Every qualifying substring corresponds to a pair of occurrences — one for the start, one for the end, with the start no later than the end — so the answer is m choose 2 plus the m single-character substrings, which is m(m+1)/2.
Approach
- Count how many times
cappears ins. - Return
m * (m + 1) / 2.
Why it works
Everything between the two chosen occurrences is irrelevant — the substring is fixed once its endpoints are. That turns an apparent O(n²) enumeration into a single count, which is what the 10⁴ bound is really testing. The + m term is easy to lose: an occurrence paired with itself is a valid length-one substring.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Length-one substrings count — do not use
m * (m - 1) / 2. - Enumerating substrings directly is O(n²) and far too slow at the upper bound.
m * (m + 1)is always even, so the integer division is exact.
Reference solution
Python
def countSubstrings(s: str, c: str) -> int:
m = s.count(c)
return m * (m + 1) // 2JavaScript
var countSubstrings = function(s, c) {
var m = 0;
for (var i = 0; i < s.length; i++) if (s.charAt(i) === c) m++;
return m * (m + 1) / 2;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.