Substrings That Begin and End With the Same Letter — LeetCode 2083 Python Solution

MediumLeetCode PremiumHash TableMathStringCountingPrefix Sum
Problem
#2083
Pattern
Prefix Sum
Reading time
2 min

The 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.

Example

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".

Python solution

Python
class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        cnt = Counter()
        ans = 0
        for c in s:
            cnt[c] += 1
            ans += cnt[c]
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string \textit{s}
SpaceO(|\Sigma|), where \Sigma is the character set auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2083. Substrings That Begin and End With the Same Letter is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2083. Substrings That Begin and End With the Same Letter?
LeetCode 2083. Substrings That Begin and End With the Same Letter is rated Medium on LeetCode.
What is the time complexity of LeetCode 2083. Substrings That Begin and End With the Same Letter?
The Python solution on this page runs in O(n), where n is the length of the string \textit{s}.
What is the space complexity of LeetCode 2083. Substrings That Begin and End With the Same Letter?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the character set auxiliary space.
What topics does LeetCode 2083. Substrings That Begin and End With the Same Letter cover?
LeetCode 2083. Substrings That Begin and End With the Same Letter is tagged Hash Table, Math, String, Counting and Prefix Sum on LeetCode.
Is LeetCode 2083. Substrings That Begin and End With the Same Letter a premium problem?
Yes. LeetCode 2083. Substrings That Begin and End With the Same Letter is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview