Number of Same-End Substrings — LeetCode 2955 Python Solution

MediumLeetCode PremiumArrayHash TableStringCountingPrefix Sum
Problem
#2955
Pattern
Prefix Sum
Reading time
3 min

The problem

You are given a 0-indexed string s, and a 2D array of integers queries, where queries[i] = [li, ri] indicates a substring of s starting from the index li and ending at the index ri (both inclusive), i.e. s[li..ri].

Example

Input
s = "abcaab", queries = [[0,0],[1,4],[2,5],[0,5]]
Output
[1,5,5,10]
Explanation
Here is the same-end substrings of each query:

Python solution

Python
class Solution:
    def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]:
        n = len(s)
        cs = set(s)
        cnt = {c: [0] * (n + 1) for c in cs}
        for i, a in enumerate(s, 1):
            for c in cs:
                cnt[c][i] = cnt[c][i - 1]
            cnt[a][i] += 1
        ans = []
        for l, r in queries:
            t = r - l + 1
            for c in cs:
                x = cnt[c][r + 1] - cnt[c][l]
                t += x * (x - 1) // 2
            ans.append(t)
        return ans

Complexity

MeasureComplexity
TimeO((n + m) \times |\Sigma|)
SpaceO(n \times |\Sigma|) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2955. Number of Same-End Substrings 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 2955. Number of Same-End Substrings?
LeetCode 2955. Number of Same-End Substrings is rated Medium on LeetCode.
What is the time complexity of LeetCode 2955. Number of Same-End Substrings?
The Python solution on this page runs in O((n + m) \times |\Sigma|).
What is the space complexity of LeetCode 2955. Number of Same-End Substrings?
The Python solution on this page uses O(n \times |\Sigma|) auxiliary space.
What topics does LeetCode 2955. Number of Same-End Substrings cover?
LeetCode 2955. Number of Same-End Substrings is tagged Array, Hash Table, String, Counting and Prefix Sum on LeetCode.
Is LeetCode 2955. Number of Same-End Substrings a premium problem?
Yes. LeetCode 2955. Number of Same-End Substrings 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