Count Substrings Starting and Ending with Given Character - Problem
Given a string s and a character c, you need to find the total number of substrings that start and end with the character c.
A substring is a contiguous sequence of characters within a string. For example, in the string "hello", "ell" is a substring but "hlo" is not.
Key Points:
- Both single character
ccounts as a valid substring (starts AND ends withc) - The substring must be contiguous
- We're looking for ALL possible substrings, not just unique ones
Example: If s = "abcab" and c = 'a', the valid substrings are: "a" (index 0), "abca" (index 0-3), "a" (index 3). So the answer is 3.
Input & Output
example_1.py — Basic Case
$
Input:
s = "ababa", c = 'a'
›
Output:
6
💡 Note:
The substrings starting and ending with 'a' are: "a" (index 0), "aba" (index 0-2), "ababa" (index 0-4), "a" (index 2), "aba" (index 2-4), "a" (index 4). Total = 6.
example_2.py — Single Character
$
Input:
s = "aa", c = 'a'
›
Output:
3
💡 Note:
The substrings are: "a" (index 0), "aa" (index 0-1), "a" (index 1). With 2 occurrences of 'a', we get 2×3/2 = 3 substrings.
example_3.py — No Matches
$
Input:
s = "xyz", c = 'a'
›
Output:
0
💡 Note:
There are no occurrences of 'a' in the string, so no substrings can start and end with 'a'. The result is 0.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters
- c is a lowercase English letter
- Time limit: 1 second
Visualization
Tap to expand
Understanding the Visualization
1
Identify all positions
Mark every position where character 'c' appears in the string
2
Count total positions
Let n be the total number of positions where 'c' appears
3
Apply combination formula
Calculate n×(n+1)/2 which gives us all possible pairs including self-pairs
Key Takeaway
🎯 Key Insight: Instead of checking all possible substrings, we use combinatorics. If there are n occurrences of character c, there are exactly n×(n+1)/2 valid substrings - this includes both single characters and all possible pairs between positions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code