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
Count Substrings: s="abaca", c="a"Find all substrings that start AND end with character "a"abaca024Valid Substrings:Single chars: a₀, a₂, a₄Between pairs: a₀a₂, a₀a₄, a₂a₄Total: 3 + 3 = 6Formula: n × (n + 1) ÷ 2 = 3 × 4 ÷ 2Result: 6
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
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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