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
Mathematical Insight: nร—(n+1)/2 FormulaExample: "abab" โ†’ 'a' appears 2 times, 'b' appears 2 timesababFor character 'a' (appears 2 times):Single character substrings: "a"โ‚€, "a"โ‚‚Multi-character substrings: "aba"โ‚€โ‚‹โ‚‚Total for 'a': 2ร—3/2 = 3 substringsFor character 'b' (appears 2 times):Single character substrings: "b"โ‚, "b"โ‚ƒMulti-character substrings: "bab"โ‚โ‚‹โ‚ƒTotal for 'b': 2ร—3/2 = 3 substringsFinal AnswerTotal = 3 + 3 = 6 substringsTime: O(n) | Space: O(1)
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.
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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