Count Substrings Starting and Ending with Given Character - Problem
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
A substring is a contiguous sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abaca", c = "a"
›
Output:
6
💡 Note:
The substrings starting and ending with 'a' are: "a" (position 0), "a" (position 2), "a" (position 4), "aba", "abaca", and "aca". Total count is 6.
Example 2 — No Matches
$
Input:
s = "abc", c = "z"
›
Output:
0
💡 Note:
Character 'z' doesn't appear in string "abc", so no substrings can start and end with 'z'.
Example 3 — Single Character
$
Input:
s = "a", c = "a"
›
Output:
1
💡 Note:
Only one substring "a" exists, and it starts and ends with 'a'.
Constraints
- 1 ≤ s.length ≤ 105
- c is a single lowercase English letter
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s and target character c
2
Process
Count occurrences of c and apply combination formula
3
Output
Total number of valid substrings
Key Takeaway
🎯 Key Insight: When a character appears n times, you can form exactly n×(n+1)/2 substrings that start and end with it
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code