The Number of Same-End Substrings problem asks you to count substrings that start and end with the same character. This Number of Same-End Substrings coding problem uses prefix frequency counting to efficiently compute the answer for each ending character.
Sprinklr and Google ask this to test prefix sum combined with frequency counting. For each character c and position i, the number of substrings ending at i with the same first and last character c equals the count of previous occurrences of c in s[0..i-1] plus 1 (the single character). The array, hash table, counting, string, and prefix sum interview pattern is directly applied.
Running frequency count. Maintain a frequency array freq[26]. For each position i with character c = s[i]: the substrings starting and ending with c that end at i = freq[c] + 1 (freq[c] previous starts, plus the single character [i..i]). Add this to total. Increment freq[c]. Return total.
s = "abcba".
freq[c] without adding 1 for the current position."Count substrings starting and ending with same character" is a classic prefix frequency problem. For each position, the count contribution = 1 + (previous occurrences of the same character). This O(n) single-pass solution is far more efficient than checking all O(n²) substrings. Practice similar prefix-frequency problems: "count subarrays with equal first and last elements," "count palindromic substrings by character." The running frequency approach generalizes to many substring counting problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sender With Largest Word Count | Medium | Solve | |
| Change Minimum Characters to Satisfy One of Three Conditions | Medium | Solve | |
| Subdomain Visit Count | Medium | Solve | |
| Find the Most Common Response | Medium | Solve | |
| Number of Divisible Substrings | Medium | Solve |