Number of Same-End Substrings - 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].

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcba", queries = [[0,4],[1,3]]
Output: [7,4]
💡 Note: For query [0,4] (whole string): 'a' appears 2 times → 3 substrings, 'b' appears 2 times → 3 substrings, 'c' appears 1 time → 1 substring. Total: 7. For query [1,3] ("bcb"): 'b' appears 2 times → 3 substrings, 'c' appears 1 time → 1 substring. Total: 4.
Example 2 — Single Character
$ Input: s = "aaaa", queries = [[0,3]]
Output: [10]
💡 Note: All characters are 'a', appearing 4 times. Using formula: 4×5/2 = 10 same-end substrings.
Example 3 — No Repeats
$ Input: s = "abcd", queries = [[0,3],[1,2]]
Output: [4,2]
💡 Note: For [0,3]: each character appears once, so 1×2/2 × 4 = 4. For [1,2]: 'b' and 'c' each appear once, so 1×2/2 × 2 = 2.

Constraints

  • 1 ≤ s.length ≤ 104
  • 1 ≤ queries.length ≤ 104
  • s consists of only lowercase English letters
  • 0 ≤ li ≤ ri < s.length

Visualization

Tap to expand
Number of Same-End Substrings INPUT String s: a 0 b 1 c 2 b 3 a 4 Queries: [0, 4] --> "abcba" [1, 3] --> "bcb" Same-End Substring: t[0] == t[n-1] First char = Last char "a", "aba", "bcb" OK "ab", "abc" NOT ALGORITHM STEPS 1 Prefix Count Array Count each char up to index i idx: 0 1 2 3 4 5 a: [0, 1, 1, 1, 1, 2] b: [0, 0, 1, 1, 2, 2] c: [0, 0, 0, 1, 1, 1] 2 For Each Query [l, r] Get char count in range 3 Count Same-End Pairs cnt[c] = prefix[r+1] - prefix[l] For each char c: ans += cnt*(cnt+1)/2 4 Sum All Characters Total = sum of all pairs FINAL RESULT Query [0,4]: "abcba" Same-end substrings: Length 1: a,b,c,b,a = 5 Length 3: aba, bcb = 2 Length 5: abcba = 0 a:2*(2+1)/2=3, b:2*(2+1)/2=3 c:1*(1+1)/2=1 | Total=7 Query [1,3]: "bcb" Same-end substrings: Length 1: b,c,b = 3 Length 3: bcb = 1 b:2*(3)/2=3, c:1 | Total=4 Output: [7, 4] Key Insight: Use prefix sums to count character frequencies in O(1) per query. For each character with count k in the range, there are k*(k+1)/2 same-end substrings (k single chars + C(k,2) pairs). Time: O(n + q*26) where n=string length, q=queries. Space: O(26*n) for prefix arrays. TutorialsPoint - Number of Same-End Substrings | Optimal Solution
Asked in
Google 45 Microsoft 38 Amazon 32 Facebook 28
18.5K Views
Medium Frequency
~25 min Avg. Time
892 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