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
Same-End Substrings ProblemInput: s = "abcba", queries = [[0,4], [1,3]]abcba01234Query [0,4]a: 2 → 3 substringsb: 2 → 3 substringsc: 1 → 1 substringQuery [1,3]b: 2 → 3 substringsc: 1 → 1 substringResult: 7Result: 4Output: [7, 4]
Understanding the Visualization
1
Input
String s and query ranges
2
Process
Count character frequencies in each range
3
Output
Apply formula n*(n+1)/2 for each character
Key Takeaway
🎯 Key Insight: For n identical characters, there are exactly n×(n+1)/2 same-end substrings possible
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