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
Count Substrings: Same Start and End CharacterInput: "abaca"abacaCount frequencies: a=3, b=1, c=1Character 'a': 3×4÷2 = 6 substringsCharacter 'b': 1×2÷2 = 1 substringCharacter 'c': 1×2÷2 = 1 substringValid substrings: "a", "aba", "abaca", "a", "aca", "a", "b", "c"Total: 8
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
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen