Substrings That Begin and End With the Same Letter Problem
#2083
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2083.
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.
Example 1:
Input: s = "abcba"
Output: 7
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "c", "b", and "a".
The substring of length 3 that starts and ends with the same letter is: "bcb".
The substring of length 5 that starts and ends with the same letter is: "abcba".
Example 2:
Input: s = "abacad"
Output: 9
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "a", "c", "a", and "d".
The substrings of length 3 that start and end with the same letter are: "aba" and "aca".
The substring of length 5 that starts and ends with the same letter is: "abaca".
Example 3:
Input: s = "a"
Output: 1
Explanation:
The substring of length 1 that starts and ends with the same letter is: "a".
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters.
Solution
Approach: Count Occurrences While Scanning
A substring that begins and ends with the same letter is fixed by choosing its end position and an earlier-or-equal start position holding the same letter. So when we reach a character c that has appeared cnt[c] times (including this one), exactly cnt[c] substrings end here: the single letter itself and one for each earlier c.
Scan the string, increment cnt[c], and add cnt[c] to the answer.
Complexity: Time O(n), space O(26).
class Solution:
def numberOfSubstrings(self, s: str) -> int:
cnt = Counter()
ans = 0
for c in s:
cnt[c] += 1
ans += cnt[c]
return ans