Substrings That Begin and End With the Same Letter - Problem
Given a string s consisting of only lowercase English letters, your task is to count how many substrings begin and end with the same character.
A substring is a contiguous sequence of characters within the string. For example, in the string "abc", the substrings are: "a", "b", "c", "ab", "bc", and "abc".
Key insight: Every single character forms a valid substring by itself! For the string "abcab", valid substrings include "a", "aba", "abcab", "b", "bcab", "c", "a", and "b".
Return the total count of such substrings.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aba"
โบ
Output:
4
๐ก Note:
The valid substrings are: "a" (index 0), "aba" (indices 0-2), "b" (index 1), "a" (index 2). Total count = 4.
example_2.py โ All Different
$
Input:
s = "abc"
โบ
Output:
3
๐ก Note:
Each character forms a valid substring by itself: "a", "b", "c". No multi-character substrings have matching start and end. Total count = 3.
example_3.py โ All Same
$
Input:
s = "aaa"
โบ
Output:
6
๐ก Note:
Valid substrings are: "a"โ, "a"โ, "a"โ, "aa"โโโ, "aa"โโโ, "aaa"โโโ. With 3 'a's, we get 3ร4/2 = 6 total substrings.
Constraints
- 1 โค s.length โค 1000
- s consists of lowercase English letters only
- No empty string inputs
Visualization
Tap to expand
Understanding the Visualization
1
Count Frequencies
Scan the string once to count how many times each character appears
2
Apply Combinatorics
For n occurrences of a character, there are n single-char substrings plus C(n,2) multi-char substrings = nร(n+1)/2 total
3
Sum All Characters
Add up the contributions from each distinct character to get the final answer
Key Takeaway
๐ฏ Key Insight: The combinatorics formula nร(n+1)/2 counts both single-character substrings and all possible multi-character substrings with matching endpoints, eliminating the need for nested loops.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code