VOOZH about

URL: https://www.geeksforgeeks.org/dsa/ascii-range-sum/

⇱ ASCII Range Sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ASCII Range Sum

Last Updated : 28 Jul, 2025

Given a string s consisting of lowercase English letters, identify all characters whose first and last occurrences are at different positions.
For each such character, compute the sum of ASCII values of all characters that lie strictly between its first and last occurrence.
Return a list of all non-zero sums. The order of sums does not matter.

Examples:

Input: s = "abacab"
Output: [293, 294]
Explanation: characters 'a' and 'b' appear more than one:
'a' : between positions 1 and 5 → characters are b, a, c and ascii sum is 98 + 97 + 99 = 294.
'b' : between positions 2 and 6 → characters are a, c, a and ascii sum is 97 + 99 + 97 = 293.

Input: s = "acdac"
Output: [197, 199]
Explanation: characters 'a' and 'c' appear more than one:
'a'  :  between positions 1 and 4 → characters are c, d and ascii sum is  99 + 100 = 199.
'c'  :  between positions 2 and 5 → characters are d, a and ascii sum is  100 + 97  = 197.

[Approach 1] - First-Last Index Brute Sum

In this approach, we first record the indices of all occurrences for each character in the string. For every character that appears more than once, we identify its first and last occurrence. Then, we traverse the substring strictly between these two positions and compute the sum of ASCII values of all characters in that range. Finally, we collect all such non-zero sums and return them. This method is simple but inefficient, as it may repeatedly scan large parts of the string for multiple characters.


Output
293 294 

Time Complexity: O(n) where n is the length of string. Note that result vector will be of size 26 so ignore 26*log(26) while sorting.
Auxiliary space: O(n) storing the positions of each characters.

[Approach 2] Using Prefix Sum - O(n) Time and O(n) Space

The idea is to use prefix sums to quickly calculate the ASCII values between the first and last occurrences of each character in the string. We track these positions for each character, and use a prefix sum array to get the range sum in constant time. Only non-zero sums are collected. This makes the approach both efficient and easy to follow.


Output
293 294 

[Expected Approach] Space-Optimized Range Sum Using First and Last Indices - O(n) Time and O(1) Space

In this approach, we avoid using extra space like a prefix sum array by directly scanning character ranges when needed. We first record the first and last occurrence of each character using two fixed-size arrays (since there are only 26 lowercase letters). Then, for every character that appears more than once, we compute the sum of ASCII values of characters strictly between its first and last positions by iterating over that range.


Output
293 294 
Comment
Article Tags: