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 <= 105s and c consist only of lowercase English letters.In this approach, we use the two-pointers method to find positions where the substring starts and ends with the character 'c'. We have a simple count of all such occurrences using combinations.
We iterate through the string, and every time we see the character 'c', we increment a counter 'prevCount' representing the number of 'c' encountered so far. This counter is added to a global 'count' which keeps track of all valid substrings ending at the current position. This way, we consider all substrings formed with the current 'c' as an endpoint.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(1)
This approach involves precomputing all positions of the character 'c' and then using combinations of these positions to calculate the number of valid substrings.
This method involves first storing all positions of the character 'c' in an array. For each of these positions (let's call one of them start), there are valid substrings with this position as the start for every subsequent position in the list. So, we just need to consider combinations of start-end pairs.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Approach 1: Two-Pointers and Counting | Time Complexity: O(n), Space Complexity: O(1) |
| Approach 2: Precomputing Positions of Character | Time Complexity: O(n), Space Complexity: O(n) |
3084. Count Substrings Starting and Ending with Given Character | Math | Sum of n Natural Numbers • Aryan Mittal • 2,376 views views
Watch 9 more video solutions →Practice Count Substrings Starting and Ending with Given Character with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor