#3084

Count Substrings Starting and Ending with Given Character

Medium
MathStringCountingCountingCombinatorial Mathematics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all possible substrings, we can count the occurrences of the character and use combinatorial mathematics to calculate the number of valid substrings directly. This is much more efficient.

⚙️

Algorithm

2 steps
  1. 1Step 1: Count the total occurrences of the character c in the string s. Let this count be m.
  2. 2Step 2: Use the formula m * (m + 1) / 2 to calculate the total number of substrings that start and end with c. This works because each pair of occurrences can form a substring.
solution.py8 lines
1# Full working Python code
2
3def count_substrings(s, c):
4    m = s.count(c)
5    return m * (m + 1) // 2
6
7# Example usage
8print(count_substrings('abada', 'a'))  # Output: 6

Complexity note: The time complexity is O(n) because we only traverse the string once to count occurrences of c. The space complexity is O(1) since we use a constant amount of extra space.

  • 1Counting occurrences can simplify problems involving substrings.
  • 2Using combinatorial mathematics can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.