Substrings That Begin and End With the Same Letter - Problem
You are given a 0-indexed string s consisting of only lowercase English letters. Return the number of substrings in s that begin and end with the same character.
A substring is a contiguous non-empty sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abaca"
›
Output:
8
💡 Note:
Character 'a' appears 3 times: forms 3×4÷2=6 substrings. Characters 'b' and 'c' each appear once: each forms 1 substring. Total: 6+1+1=8
Example 2 — Single Character
$
Input:
s = "aa"
›
Output:
3
💡 Note:
Character 'a' appears 2 times: forms 2×3÷2=3 substrings ("a", "a", "aa")
Example 3 — All Different
$
Input:
s = "abc"
›
Output:
3
💡 Note:
Each character appears once: each forms 1 substring. Total: 1+1+1=3
Constraints
- 1 ≤ s.length ≤ 105
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with lowercase letters
2
Process
Count character frequencies and apply formula
3
Output
Total number of valid substrings
Key Takeaway
🎯 Key Insight: Each character contributes n×(n+1)/2 substrings where n is its frequency
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code