Number of Same-End Substrings Problem
Description
LeetCode Problem 2955.
You are given a 0-indexed string s, and a 2D array of integers queries, where queries[i] = [l_i, r_i] indicates a substring of s starting from the index l_i and ending at the index r_i (both inclusive), i.e. s[l_i..r_i].
Return an array ans where ans[i] is the number of same-end substrings of queries[i].
A 0-indexed string t of length n is called same-end if it has the same character at both of its ends, i.e., t[0] == t[n - 1].
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
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:
1^st query: s[0..0] is "a" which has 1 same-end substring: "a".
2^nd query: s[1..4] is "bcaa" which has 5 same-end substrings: "bcaa", "bcaa", "bcaa", "bcaa", "bcaa".
3^rd query: s[2..5] is "caab" which has 5 same-end substrings: "caab", "caab", "caab", "caab", "caab".
4^th query: s[0..5] is "abcaab" which has 10 same-end substrings: "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab".
Example 2:
Input: s = "abcd", queries = [[0,3]]
Output: [4]
Explanation: The only query is s[0..3] which is "abcd". It has 4 same-end substrings: "abcd", "abcd", "abcd", "abcd".
Constraints:
2 <= s.length <= 3 * 10^4sconsists only of lowercase English letters.1 <= queries.length <= 3 * 10^4queries[i] = [l_i, r_i]0 <= l_i <= r_i < s.length
Solution
Approach: Prefix Counts
Build, for each letter, a prefix count array so that the number of occurrences of any letter in any range [l, r] is a subtraction.
For a query, a letter that occurs x times in the range gives x * (x - 1) / 2 substrings that start and end on two different occurrences of it. Each single character is also a valid substring, which adds r - l + 1. Sum over the 26 letters.
Complexity: O((n + q) * 26) time and O(26 * n) space, where n is the length of s and q the number of queries.
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