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 c counts as a valid substring (starts AND ends with c)
  • 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
Mathematical Insight: CombinationsString: "ababa" with c = 'a'apos 0apos 2apos 4"aba""ababa""aba""a""a""a"Formula: n × (n + 1) ÷ 2where n = number of occurrences of character cIn our example: 3 × 4 ÷ 2 = 6This counts all pairs: (0,0), (0,2), (0,4), (2,2), (2,4), (4,4)🎯 Key Insight: Choose 2 positions from n with repetition = C(n+1,2)Time: O(n) | Space: O(1)Just count occurrences and apply the formula!
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K 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