3084. Count Substrings Starting and Ending with Given Character LeetCode Solution

In this guide, you will get 3084. Count Substrings Starting and Ending with Given Character LeetCode Solution with the best time and space complexity. The solution to Count Substrings Starting and Ending with Given Character problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Substrings Starting and Ending with Given Character solution in C++
  4. Count Substrings Starting and Ending with Given Character solution in Java
  5. Count Substrings Starting and Ending with Given Character solution in Python
  6. Additional Resources
3084. Count Substrings Starting and Ending with Given Character LeetCode Solution image

Problem Statement of Count Substrings Starting and Ending with Given Character

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 <= 105
s and c consist only of lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3084. Count Substrings Starting and Ending with Given Character LeetCode Solution in C++

class Solution {
 public:
  long long countSubstrings(string s, char c) {
    const int freq = ranges::count(s, c);
    return static_cast<long>(freq) * (freq + 1) / 2;
  }
};
/* code provided by PROGIEZ */

3084. Count Substrings Starting and Ending with Given Character LeetCode Solution in Java

class Solution {
  public long countSubstrings(String s, char c) {
    final long freq = s.chars().filter(ch -> ch == c).count();
    return freq * (freq + 1) / 2;
  }
}
// code provided by PROGIEZ

3084. Count Substrings Starting and Ending with Given Character LeetCode Solution in Python

class Solution:
  def countSubstrings(self, s: str, c: str) -> int:
    freq = s.count(c)
    return freq * (freq + 1) // 2
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.