Count Substrings Starting and Ending with Given Character Problem
#3084
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3084.
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
Example 1:
Input: s = "abada", c = "a"
Output: 6
Explanation: Substrings starting and ending with "a" are: "abada", "abada", "abada", "abada", "abada", "abada".
Example 2:
Input: s = "zzz", c = "z"
Output: 6
Explanation: There are a total of 6 substrings in s and all start and end with "z".
Constraints:
1 <= s.length <= 10^5sandcconsist only of lowercase English letters.
Solution
Approach: Mathematics
Let cnt be the number of occurrences of c. Each occurrence alone is a valid substring (cnt of them), and each pair of different occurrences gives one more, cnt * (cnt - 1) / 2. The answer is cnt + cnt * (cnt - 1) / 2.
Complexity: O(n) time, O(1) space.
class Solution:
def countSubstrings(self, s: str, c: str) -> int:
cnt = s.count(c)
return cnt + cnt * (cnt - 1) // 2