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 Starting and Ending with Given Character INPUT String s = "abaca" a 0 b 1 a 2 c 3 a 4 Target char c = 'a' a All valid substrings: "a" (pos 0) "aba" (0-2) "abaca" (0-4) "a" (pos 2) "aca" (2-4) "a" (pos 4) Count of 'a' = 3 (at positions 0, 2, 4) ALGORITHM STEPS 1 Count occurrences Count char c in string s count = 3 ('a' appears 3x) 2 Apply formula n * (n + 1) / 2 = 3 * (3+1) / 2 3 Calculate 3 * 4 / 2 = 12 / 2 = 6 4 Return result Return 6 as answer Why this formula works: Each 'a' can pair with itself and all 'a's after it. This is sum: 1+2+...+n FINAL RESULT 6 substrings Verification: "a" (idx 0) "a" (idx 2) "a" (idx 4) "aba" "aca" "abaca" 3 single 'a' + 2 pairs + 1 triple = 3 + 2 + 1 = 6 OK Output matches! Key Insight: If character c appears n times in string s, each occurrence can form a valid substring with itself and every subsequent occurrence. This gives us the triangular number formula: n*(n+1)/2. Time Complexity: O(n) | Space Complexity: O(1) - Optimal single-pass solution! TutorialsPoint - Count Substrings Starting and Ending with Given Character | Optimal Solution
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