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
Substrings Beginning and Ending with Same Letter INPUT String s = "abaca" a idx 0 b idx 1 a idx 2 c idx 3 a idx 4 Character Frequency Char Count Pairs a 3 6 b 1 1 c 1 1 Total: 6 + 1 + 1 = 8 ALGORITHM STEPS 1 Count Characters Track frequency of each letter in the string 2 Apply Formula For count n, substrings = n*(n+1)/2 3 Calculate Each a: 3*(3+1)/2 = 6 b: 1*(1+1)/2 = 1 c: 1*(1+1)/2 = 1 4 Sum All Results Add results for all unique characters Formula: n*(n+1)/2 (Counts all substrings for char) FINAL RESULT Answer 8 All 8 Substrings: "a" (idx 0) "a" (idx 2) "a" (idx 4) "aba" (0-2) "aca" (2-4) "abaca" (0-4) "b" (idx 1) "c" (idx 3) Verification 6 (a) + 1 (b) + 1 (c) = 8 OK - Matches expected output! Complexity Time: O(n) | Space: O(1) (26 letters constant space) Key Insight: Instead of checking all O(n^2) substrings, use counting! For each character appearing n times, the number of substrings starting and ending with it equals n*(n+1)/2. This counts single chars (n times) plus pairs of same chars (n choose 2). Sum across all characters for O(n) solution. TutorialsPoint - Substrings That Begin and End With the Same Letter | Optimal Solution
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